我正在嘗試將未登錄到我的應用程式的用戶重定向到登錄頁面,并且我的路由檔案中的 useEffect 中有一些條件,但是當我輸入其中之一時,重定向不起作用并且我想知道它是否與 react-router-dom 有關
Route.js 檔案代碼如下:
import React, { useEffect } from 'react'; // nao estava
import { PropTypes } from 'prop-types';
import { Route, Redirect, useHistory } from 'react-router-dom';
import AuthLayout from '../pages/_layouts/auth';
import DefaultLayout from '../pages/_layouts/default';
import { store } from '../store';
export default function RouteWrapper({
component: Component,
isPrivate,
...rest
}) {
const { signed } = store.getState().auth;
const { googleSigned } = store.getState().googleAuth;
const history = useHistory();
useEffect(() => {
if (!signed && !googleSigned && isPrivate) {
return <Redirect to="/" />;
}
if ((signed && !isPrivate) || (googleSigned && !isPrivate)) {
return <Redirect to="/dashboard" />;
}
return <Redirect to="#" />;
}, [googleSigned, signed]);
const Layout =
signed || googleSigned || window.location.pathname === '/dashboard'
? DefaultLayout
: AuthLayout;
return (
<Route
{...rest}
render={(props) => (
<Layout>
<Component {...props} />
</Layout>
)}
/>
);
}
RouteWrapper.propTypes = {
isPrivate: PropTypes.bool,
component: PropTypes.oneOfType([PropTypes.element, PropTypes.func])
.isRequired,
};
RouteWrapper.defaultProps = {
isPrivate: false,
};
signed 和 googleSigned 是存在于 reducer 中的狀態,焦點是 google 簽名,因為使用正常登錄獲得的簽名尚未實作,而 google 簽名是在應用程式后端使用 oAuth 實作的
此時我的應用程式的流程如下,用戶單擊 google 上的登錄按鈕被重定向到 google 身份驗證螢屏,如果用戶在應用程式中注冊,他將被重定向到儀表板頁面、儀表板頁面并發送操作檢查用戶是否登錄到應用程式,目的是如果用戶未登錄(googleSigned = false),他將被重定向回登錄頁面
uj5u.com熱心網友回復:
您的實施存在一些問題。首先也是最重要的,回報useEffect并不像你希望的那樣作業。回傳useEffect實際上用于清除副作用,例如滾動偵聽器或類似的,您不想在組件卸載后保留。您可以在此處閱讀更多相關資訊:https : //reactjs.org/docs/hooks-effect.html。
您想要做的是以編程方式重定向用戶,而不是回傳重定向組件。有了react-router-dom您可以使用做useHistory鉤子(https://reactrouter.com/web/api/Hooks/usehistory)。因此,我們可以使用歷史代替回傳鉤子中的<Redirect />組件useEffect。
useEffect(() => {
if (!signed && !googleSigned && isPrivate) {
history.push("/");
}
if ((signed && !isPrivate) || (googleSigned && !isPrivate)) {
history.push("/dashboard");
}
history.push("#");
}, [googleSigned, signed]);
像上面這樣的東西應該更接近你想要實作的目標。
uj5u.com熱心網友回復:
也許您想實作受保護的路由模式?
保護路線
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/337248.html
