我正在構建一個使用 react 和 firebase 的應用程式。我創建了一個登錄組件,它在登錄后將狀態“isLoggedIn”設定為 true 并將用戶重定向到主頁。問題是狀態默認為false,需要時間來設定,所以重繪 主頁面的時候,可以簡單的看到登錄頁面。我是否更改路由器重定向代碼或以不同方式設定狀態?
這是我的代碼:
const [isLoggedIn, setIsLoggedIn] = useState(false)
onAuthStateChanged(auth, (currentUser) => {
setIsLoggedIn(currentUser)
})
return (
<Router>
{isLoggedIn ? <Redirect to="/home" /> : <Redirect to="/login" />}
<Route path="/home" component={SongList} />
<Route path="/login" component={Auth} />
</Router>
)
uj5u.com熱心網友回復:
在react-router-domv5 中,常見的模式是創建一個自定義路由組件來處理 auth 狀態,即使它是 pending。創建一個AuthRoute從不確定狀態開始的組件,并且在您獲得身份驗證確認之前不要呈現路由的組件或重定向。
例子:
const AuthRoute = props => {
const location = useLocation();
const [isLoggedIn, setIsLoggedIn] = useState(); // <-- neither true nor false
useEffect(() => {
const unsubscribe = onAuthStateChanged(auth, (currentUser) => {
setIsLoggedIn(currentUser); // sets user object or null
});
return unsubscribe; // <-- cleanup auth subscription!
}, []);
if (isLoggedIn === undefined) return null; // <-- or loading indicator, etc...
return isLoggedIn ? (
<Route {...props} />
) : (
<Redirect
to={{
pathname: "/login",
state: { location }, // <-- pass current location
}}
/>
);
};
用法:
<Router>
<Switch> // <-- match & render a single route
<AuthRoute path="/home" component={SongList} />
<Route path="/login" component={Auth} />
</Switch>
</Router>
在Auth組件訪問location從路由狀態和成功登錄后,您可以將用戶重定向回他們最初嘗試訪問的路由。
const { state } = useLocation();
const history = useHistory();
...
// successful login, redirect back to route, or home if undefined
history.replace(state.location?.pathname ?? "/home")
PrivateRoute盡管您將進行大量身份驗證檢查,但讓每個“實體”保持自己的狀態。從這里開始,您可能想要實作一個AuthProviderReact 背景關系組件來存盤isLoggedIn狀態,并且每個PrivateRoute組件都訂閱背景關系值。通過這種方式,用戶登錄應用程式后可以保持此狀態,而無需在每次訪問受保護的路由時重新檢查/獲取它。
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/364461.html
標籤:反应 重定向 Firebase 身份验证 反应路由器-dom
上一篇:如何在Button的onClick功能之后或期間重定向?
下一篇:不發送郵件的聯系表7條件重定向
