react JS中的私有路由jsx
Posted
技术标签:
【中文标题】react JS中的私有路由jsx【英文标题】:Private Route jsx in react JS 【发布时间】:2021-06-04 15:44:31 【问题描述】:问题:我正在尝试通过 isAuth()
助手对用户进行身份验证,但它的行为很奇怪。我希望它查找访问令牌(如果有)或从后端调用访问令牌(如果刷新令牌可用),虽然它可以完美运行并设置访问令牌 cookie,但问题是如果从 PrivateRoutes.jsx
调用,它看不到令牌根本没有并将用户发送到登录页面。
为 refs 添加所需的代码:
isAuth():
export const isAuth = () =>
if (window !== undefined)
const accessCookieChecked = getCookie("_mar_accounts_at");
const refreshCookieChecked = getCookie("_mar_accounts_rt");
if (accessCookieChecked)
return true;
else if (refreshCookieChecked)
console.log(refreshCookieChecked);
axios(
method: "POST",
url: `$API_URL/api/token`,
data: refresh_token: refreshCookieChecked ,
).then((res) =>
console.log(res);
setCookie("_mar_accounts_at", res.data.accessToken);
return true;
);
else
return false;
else
return false;
;
PrivateRoutes.jsx
import React from "react";
import Route, Redirect from "react-router-dom";
import isAuth from "../helpers/auth";
const PrivateRoute = ( component: Component, ...rest ) => (
<Route
...rest
render=(props) =>
isAuth() ? (
<Component ...props />
) : (
<Redirect
to= pathname: "/login", state: from: props.location
/>
)
></Route>
);
export default PrivateRoute;
有人可以看看吗?并提供帮助!
【问题讨论】:
【参考方案1】:您很可能遇到了异步问题,当您在 axios 中进行调用时,回调中的 return true;
实际上永远不会返回到您在 PrivateRoute 中的函数调用。相反,您需要使用 Promise/setState/useEffect:
export const isAuth = () =>
if (window === undefined)
return Promise.resolve(false);
else
const accessCookieChecked = getCookie("_mar_accounts_at");
const refreshCookieChecked = getCookie("_mar_accounts_rt");
if (accessCookieChecked)
return Promise.resolve(true);
else if (refreshCookieChecked)
console.log(refreshCookieChecked);
return new Promise(resolve =>
axios(
method: "POST",
url: `$API_URL/api/token`,
data: refresh_token: refreshCookieChecked ,
).then((res) =>
console.log(res);
setCookie("_mar_accounts_at", res.data.accessToken);
resolve(true);
);
)
else
return Promise.resolve(false);
;
import React, useState, useEffect from 'react';
import Route, Redirect from 'react-router-dom';
import isAuth from '../helpers/auth';
const PrivateRoute = ( component: Component, ...rest ) =>
const [isAuthTrue, setIsAuthTrue] = useState();
const [loading, setLoading] = useState(true);
useEffect(() =>
isAuth().then(res =>
setIsAuthTrue(res);
setLoading(false);
)
)
return (
<>
loading ? (
<div>some loading state</div>
) : (
<Route
...rest
render=(props) =>
isAuthTrue ? (
<Component ...props />
) : (
<Redirect
to= pathname: '/login', state: from: props.location
/>
)
/>
)
</>
);
;
export default PrivateRoute;
【讨论】:
这很好用!谢谢你。只需编辑 PrivateRoute,因为您要导入setState
而不是 useState
。并且反应也会对同名问题感到困惑。但主要问题解决了,我应该做 Promise 功能。谢谢!以上是关于react JS中的私有路由jsx的主要内容,如果未能解决你的问题,请参考以下文章
如何使用嵌套路由和私有路由组件在 react.js 中正确构建路由?