Reactjs 回应一下,为什么在重定向开始之前,我的私有路由会向未经授权的用户呈现一秒钟?
我一直在使用私有路由来保护它们,但我面临的问题是,每当未经授权的用户进入该路由时,他都能在被重定向到未经授权用户的默认路由之前短暂地看到受保护的路由内容 为什么会这样?我怀疑发生这种情况是因为我的身份验证服务依赖于外部服务器,这会导致验证延迟,在验证用户时,它会显示受保护的路由,但一旦完成验证,结果是“未经授权”,它会将用户重定向到另一个未受保护的路由 这就是我的私人路线Reactjs 回应一下,为什么在重定向开始之前,我的私有路由会向未经授权的用户呈现一秒钟?,reactjs,react-router,Reactjs,React Router,我一直在使用私有路由来保护它们,但我面临的问题是,每当未经授权的用户进入该路由时,他都能在被重定向到未经授权用户的默认路由之前短暂地看到受保护的路由内容 为什么会这样?我怀疑发生这种情况是因为我的身份验证服务依赖于外部服务器,这会导致验证延迟,在验证用户时,它会显示受保护的路由,但一旦完成验证,结果是“未经授权”,它会将用户重定向到另一个未受保护的路由 这就是我的私人路线 import { Route } from 'react-router-dom'; import React fro
import { Route } from 'react-router-dom';
import React from 'react';
import { Redirect } from 'react-router';
export default ({ component: Component, render: renderFn, authed, ...rest }) =>
Component ? (
<Route
{...rest}
render={props =>
authed === true ? (
<Component {...props} />
) : (
<Redirect to={{ pathname: '/', state: { from: props.location } }} />
)
}
/>
) : (
<Route {...rest} render={props => authed === true ? renderFn(props) : <Redirect to={{ pathname: '/', state: { from: props.location } }} /> } />
);
这就是我在componentDidMount()中看到的内容
正如您所看到的,它调用了一个身份验证服务器,我怀疑它是延迟发生的地方,这可能是未经授权的用户发生渲染的原因
import axios from 'axios'
import Cookies from 'js-cookie';
export default function isAuthenticated() {
var accesstoken = Cookies.get('accesstoken');
return axios({ method: 'post', url: 'http://localhost:3003/verify', headers: { Authorization: `Bearer ${accesstoken}` } })
.then(function (response) {
if (response.data.status === "valid") {
console.log("service valid")
return true;
} else {
console.log("service invalid")
return false;
}
});
}
我怎样才能解决这个问题?我正在考虑在PrivateRoute中添加一个包含“加载”内容或类似内容的中间页面,但我不确定如何或在何处实现它。首先,请使用严格的空检查(即:myBool===true),因为它们可以保护您不在代码中引用空值或未定义的值 对于您的问题,看起来一开始isAuthenticated总是正确的。Axios异步响应随后会自动更改该值 在app.js中,您已经将isAuthenticated值初始化为true,尝试在开始时将其设置为false,因为我猜您的所有用户都不应该在开始时进行身份验证,对吗
其他一切对我来说都很好。你是对的,问题是默认值为true,将其更改为false,现在可以正常工作了
this.state = {
isAuthenticated: true
}
componentDidMount() {
isAuthenticated().then((result) => {
if (result == true) {
this.setState({ isAuthenticated: true})
} else {
this.setState({ isAuthenticated: false})
}
});
}
import axios from 'axios'
import Cookies from 'js-cookie';
export default function isAuthenticated() {
var accesstoken = Cookies.get('accesstoken');
return axios({ method: 'post', url: 'http://localhost:3003/verify', headers: { Authorization: `Bearer ${accesstoken}` } })
.then(function (response) {
if (response.data.status === "valid") {
console.log("service valid")
return true;
} else {
console.log("service invalid")
return false;
}
});
}