【问题标题】:React - Load component after useContext returns valueReact - useContext 返回值后加载组件
【发布时间】:2021-12-01 07:11:09
【问题描述】:

所以我有 Dashboard 组件,它应该显示 currentUsers 信息。 我将我的currentUser 保留在全球context/state 中。

问题是当Dashboard 组件呈现FIRST 时间currentUsernull 即使用户实际登录。因此我在第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


    【解决方案1】:

    您可以为用户设置默认值以避免第一个错误。

    在这种情况下,您可以像这样更改您的Dashboard

    /* ... */
    
    const {
        currentUser = {
            isLoggedIn: false,
            firstName: 'first name'
        }
    } = useContext(CurrentUserContext);
    
    const [firstName, setFirstName] = useState(currentUser.firstName);
    /* ... */
    
    if (!currentUser.isLoggedIn) {
        return <Redirect to={'/login'}/>;
    }
    
    /* ... */
    

    要解决第二个问题,你需要在授权后检查你的localStorage是否真的包含user字段。

    【讨论】:

      【解决方案2】:

      我通过这样做解决了这两个问题。

      const [currentUser, setCurrentUser] = useState(null); // Replaced this line with next line
      const [currentUser, setCurrentUser] = useState(() => isLoggedIn());
      

      我删除了 useeffect,因为我不再需要它了。

      // Setting current user
      useEffect(() => {
        setCurrentUser(isLoggedIn()).catch(err => console.log(err));
      }, []);
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2020-12-08
        • 2021-07-02
        • 1970-01-01
        • 2022-01-23
        • 1970-01-01
        • 2022-01-26
        • 2020-06-12
        相关资源
        最近更新 更多