[英]How to use useCollection react-firebase hook with firebase v9
[英]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.