简体   繁体   English

如果会话在反应路由器 6 中过期,则重定向到登录页面或登录页面

[英]Redirect to login page or landing page if session expire in react with react router 6

In my React App,I need to redirect the current page to landing page if session expires, I am using the在我的 React 应用程序中,如果会话过期,我需要将当前页面重定向到登录页面,我正在使用

"react-router-dom": "^6.2.2",

My session expiration time is 60. I am doing the private routing with following approach,我的会话到期时间是 60。我正在使用以下方法进行私有路由,

export const getCurrentUser = () => async (dispatch) => {
    try {
        const res = await axios.get(BASE_URL + GET_CURRENT_USER_URL, { withCredentials: true });
        localStorage.setItem('orgId', res.data.orgId);
        dispatch({
            type: GET_CURRENT_USER,
            payload: res.data
        });

        return res.data;
    } catch (err) {
        console.log(err);
    }
};
export default function PrivateOutlet() {
    const [isLoaded, setIsLoaded] = useState(false);
    const dispatch = useDispatch();

    useEffect(() => {
        dispatch(getCurrentUser())
        .then((res) => {
            setIsLoaded(true);
            localStorage.setItem('orgId', res.orgId);
        })
        .catch(error => console.log(error) );
    }, [dispatch]);

    return   ( isLoaded ? (localStorage.getItem('orgId') !== undefined) ? <Outlet /> : <Navigate to="/landingPage" /> : <></>)

};


<Route path="/*" element={<PrivateOutlet />} >
    <Route path="home" element={<Home />} />
</Route>

By using this approach, if I reload the page it is redirecting to landing page but,If I not doing the reload and lets say I trigger any event it is showing nothing since Backend APIs are returning nothing since session has been expired.通过使用这种方法,如果我重新加载页面,它会重定向到登录页面,但是,如果我没有进行重新加载并假设我触发了任何事件,它什么都不显示,因为后端 API 没有返回任何内容,因为会话已过期。

So If session expired How I redirect the current page to landing page if I trigger any click or any event?因此,如果会话过期,如果我触发任何点击或任何事件,我如何将当前页面重定向到登录页面?

add state for error:添加错误状态:

const [isError, setIsError] = useState(false);

set error state when result is failed:结果失败时设置错误状态:

.catch(error => setIsError(true) );

and before base return with isLoaded check add:在使用 isLoaded 检查基础返回之前添加:

if (isError) {
   return <Navigate to="/landingPage" replace={true} />
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM