我正在编写客户端代码以使用React和react-router进行身份验证。在下面的代码中,我想检查服务器上的jwt令牌。之后,我将从服务器上获取response.data.access
,并在客户端上将其设置为access
变量。但是,即使它在控制台中记录了false
,似乎它仍将true
传递到了受保护的路由。如何正确设置access
?我猜问题出在异步代码中,并且调用setAccess
函数而无需等待axios提取。
// imports
function App() {
const [access, setAccess] = useState(false);
useEffect(() => {
fetch();
}, [access]);
const fetch = async () =>
await axios.get('http://localhost:7000/user/check-token')
.then(response => {
// response.data.access is a boolean variable coming from server
console.log(response.data.access)
setAccess(response.data.access);
});
return (
<Router>
<Switch>
// other routes
<Protected path='/user/dashboard' access={access}>
<Dashboard userData={userData} />
</Protected>
</Switch>
</Router>
);
}
export default App;
这是受保护的路线
const Protected = ({ children, access, ...rest }) => {
return (
<div>
<Route {...rest} render={(props) => (
access === true
? children
: <Redirect to={{
pathname: '/user/login',
state: { from: props.location }
}} />
)} />
</div>
);
}
请您说明发生了什么,我该怎么办?
答案 0 :(得分:1)
我已经解决了这个问题。好吧,我刚刚添加了一个加载屏幕,等待数据提取期间,它解决了我的问题。
Sub FillNumbers(ByVal n As Long, arr)
ReDim arr(1 To n)
arr(1) = 100
arr(2) = 200
arr(3) = 300
End Sub