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

Arc*_*Use 1 reactjs firebase-authentication

我使用React firebase hooks 库有以下代码:

\n
    // load user state \n    const [user, loadingAuthState, errorAuthState] = useAuthState(auth);\n\n    // user is loading...\n    if(loadingAuthState)\n    {\n      return <div>\xd7\x98\xd7\x95\xd7\xa2\xd7\x9f...</div>\n    }\n    // an error has occured\n    else if(errorAuthState)\n    {\n      alert(errorAuthState);\n      return <Redirect to="login"/>\n    }\n    // if the user is not set, return to the login page\n    else if(!(user))\n    {\n      return (<Redirect to="/login"/>)\n    }\n\n    // load data from the user using the user\'s ID.\n    const [value, loading, error] = useDocumentData(doc(db, "users", user.uid));\n
Run Code Online (Sandbox Code Playgroud)\n

我收到此错误:

\n
\n

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

\n
\n

我理解在顶层调用钩子的想法,但是,我需要知道用户的ID,那么如何以不与React 的指南?\n我想保留用户加载时返回的“正在加载”消息。

\n

Ana*_*lop 6

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

\n
    // load user state \n    const [user, loadingAuthState, errorAuthState] = useAuthState(auth);\n\n    // user is loading...\n    if(loadingAuthState)\n    {\n      return <div>\xd7\x98\xd7\x95\xd7\xa2\xd7\x9f...</div>\n    }\n    // an error has occured\n    else if(errorAuthState)\n    {\n      alert(errorAuthState);\n      return <Redirect to="login"/>\n    }\n    // if the user is not set, return to the login page\n    else if(!(user))\n    {\n      return (<Redirect to="/login"/>)\n    }\n\n    // load data from the user using the user's ID.\n    return <MyComponentWithUserId userId={user.uid} />\n
Run Code Online (Sandbox Code Playgroud)\n