[英]How can I use a hook after conditional statements in React?
I have this following code using the react firebase hooks library :我有以下代码使用反应 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));
I get this error:我收到此错误:
Line 46:37: React Hook "useDocumentData" is called conditionally.第 46:37 行:有条件地调用 React Hook“useDocumentData”。 React Hooks must be called in the exact same order in every component render. React Hooks 必须在每个组件渲染中以完全相同的顺序调用。 Did you accidentally call a React Hook after an early return?你是否在提前返回后不小心调用了 React Hook? react-hooks/rules-of-hooks反应钩子/钩子规则
I understand the idea of calling hooks at the top level, however, I need to know the user's ID before using the 2nd hook to read data, so how can I structure my code in a way that doesn't conflict with React's guidelines?我理解在顶层调用钩子的想法,但是,在使用第二个钩子读取数据之前我需要知道用户的 ID,那么我如何以不与 React 指南冲突的方式构建我的代码? I'd like to keep the "loading" message that is returning while the user is loading.我想保留在用户加载时返回的“正在加载”消息。
One way of doing it is to split this code into two components so that you return another component when you know the user's ID.一种方法是将此代码拆分为两个部分,以便在知道用户 ID 时返回另一个部分。 Inside of this second component you can have useDocumentData hook unconditionally because you would already know the user's ID passed in through props.在第二个组件中,您可以无条件地使用 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.