【发布时间】:2021-12-01 07:11:09
【问题描述】:
所以我有 Dashboard 组件,它应该显示 currentUsers 信息。
我将我的currentUser 保留在全球context/state 中。
问题是当Dashboard 组件呈现FIRST 时间currentUser 是null 即使用户实际登录。因此我在第14 行得到null 错误或者如果我评论仪表板指出第 22 行的 if 语句将发生,即使用户已登录,它也会重定向我。
有没有办法等待isLoggedInFunction 完成,然后执行Dashboard 组件中的逻辑?
在 App.js 中
export const CurrentUserContext = React.createContext(null); // Global Context
const [currentUser, setCurrentUser] = useState(null); // Global State
// Setting current user
useEffect(() => {
setCurrentUser(isLoggedIn()).catch(err => console.log(err));
}, []);
// IsLoggedIn Method
export function isLoggedIn() {
return localStorage.getItem('user') === null ?
null :
JSON.parse(localStorage.getItem('user'));
}
<CurrentUserContext.Provider value={{ currentUser, setCurrentUser }}> // Provider
【问题讨论】:
标签: reactjs asynchronous react-hooks state