Tai*_*chi 12 reactjs react-hooks
我是 React Hooks 新手,正在使用 React 16.13.1。
我将实现Auth能够处理登录的组件。
但它似乎没有正确更新状态currentUser,即使setCurrentUser是用响应对象调用的。
这段代码有什么问题?
import React, { useState, useEffect } from "react";
import { Route, Redirect } from "react-router-dom";
import { checkLoggedIn } from "utils/Api";
export const Auth = (props) => {
const [currentUser, setCurrentUser] = useState(null);
const [isLoading, setIsLoading] = useState(false);
console.log(currentUser);
useEffect(() => {
const f = async () => {
setIsLoading(true);
console.log(isLoading);
const res = await checkLoggedIn();
if (!!res) { // ==> true
setCurrentUser(res);
console.log(currentUser); // ==> null!
}
setIsLoading(false);
};
f();
});
if (isLoading) {
return <div>loading</div>;
}
console.log(currentUser); // ==> null!
return !!currentUser ? (
<Route children={props.children} />
) : (
<Redirect to={"/login"} />
);
};
Run Code Online (Sandbox Code Playgroud)
小智 14
setCurrentUser异步更新状态,因此不能currentUser立即使用。
但是,您可以使用另一个useEffect来了解状态何时更改:
useEffect(() => {
// currentUser changed
}, [currentUser])
Run Code Online (Sandbox Code Playgroud)
我还注意到您没有将空数组传递给useEffect已有的数组,因此每次更新组件时都会触发它。如果您useEffect只需要执行一次,则必须传递一个空数组作为第二个参数,如下所示:
useEffect(() => {
const f = async () => {
// ...
};
f();
}, []);
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
33066 次 |
| 最近记录: |