繁体   English   中英

我如何在 React 中的条件语句之后使用钩子?

[英]How can I use a hook after conditional statements in React?

我有以下代码使用反应 firebase 挂钩库

    // load user state 
    const [user, loadingAuthState, errorAuthState] = useAuthState(auth);

    // user is loading...
    if(loadingAuthState)
    {
      return <div>טוען...</div>
    }
    // an error has occured
    else if(errorAuthState)
    {
      alert(errorAuthState);
      return <Redirect to="login"/>
    }
    // if the user is not set, return to the login page
    else if(!(user))
    {
      return (<Redirect to="/login"/>)
    }

    // load data from the user using the user's ID.
    const [value, loading, error] = useDocumentData(doc(db, "users", user.uid));

我收到此错误:

第 46:37 行:有条件地调用 React Hook“useDocumentData”。 React Hooks 必须在每个组件渲染中以完全相同的顺序调用。 你是否在提前返回后不小心调用了 React Hook? 反应钩子/钩子规则

我理解在顶层调用钩子的想法,但是,在使用第二个钩子读取数据之前需要知道用户的 ID,那么我如何以不与 React 指南冲突的方式构建我的代码? 我想保留在用户加载时返回的“正在加载”消息。

一种方法是将此代码拆分为两个部分,以便在知道用户 ID 时返回另一个部分。 在第二个组件中,您可以无条件地使用 useDocumentData 挂钩,因为您已经知道通过 props 传入的用户 ID。

    // load user state 
    const [user, loadingAuthState, errorAuthState] = useAuthState(auth);

    // user is loading...
    if(loadingAuthState)
    {
      return <div>טוען...</div>
    }
    // an error has occured
    else if(errorAuthState)
    {
      alert(errorAuthState);
      return <Redirect to="login"/>
    }
    // if the user is not set, return to the login page
    else if(!(user))
    {
      return (<Redirect to="/login"/>)
    }

    // load data from the user using the user's ID.
    return <MyComponentWithUserId userId={user.uid} />

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM