javascript - ReactJs,如何等待我的函数返回一些东西
问题描述
我有一个函数调用 isAuthenticated 来检查令牌的有效性:
isAuthenticated = async () => {
const data = await request.call({
url: `http://localhost:1337/utilisateurs/VerifyUserTok`,
method: `post`,
parameters : {
authorization: `bearer ${sessionStorage.getItem(`token`)}`
}
});
if (data.IsValide){
return true;
} else {
return false;
}
}
在我的受保护路线中,如果前一个函数返回 false,我不会重定向此人。但是在 protected.route.js 文件中,该函数在第一次返回时无需等待我的 isAuthenticated 函数返回一些东西:
import React from 'react';
import { Route, Redirect } from 'react-router-dom';
import auth from './auth.js'
import NavMenu from './NavMenu';
export const ProtectedRoute = ({ component: Component, ...rest }) => {
return (
<Route
{...rest}
render = {props => {
if(auth.isAuthenticated()){
return <div className="page-body">
<Route>
<NavMenu/>
<div className="right-body">
<Component {...props}/>
</div>
</Route>
</div>
} else {
return <Redirect to={
{
pathname: "/",
state: {
from: props.location
}
}
} />
}
}}
/>
);
}
解决方案
您将需要一些状态来保存您正在寻找的信息,并且您需要在效果中执行身份验证查找。
当然,您可能会选择在进行身份验证检查时使用某种方式来显示加载指示器,但您可以根据需要找出该机制。
import React, { useState, useEffect } from 'react';
import { Route, Redirect } from 'react-router-dom';
import auth from './auth.js'
import NavMenu from './NavMenu';
export const ProtectedRoute = ({ component: Component, ...rest }) => {
const [isAuthed, setIsAuthed] = useState(false);
const [isLoaded, setIsLoaded] = useState(false);
// Assuming you just want to check on initial render
useEffect(() => {
let mounted = true;
const checkAuth = async () => {
const authed = await auth.isAuthenticated();
if (mounted) {
setIsAuthed(authed);
setIsLoaded(true);
}
checkAuth();
return () => {
mounted = false;
}
}, [])
return !isLoaded ? "Loading..." : (
<Route
{...rest}
render = {props => {
if(isAuthed){
return <div className="page-body">
<Route>
<NavMenu/>
<div className="right-body">
<Component {...props}/>
</div>
</Route>
</div>
} else {
return <Redirect to={
{
pathname: "/",
state: {
from: props.location
}
}
} />
}
}}
/>
);
}
推荐阅读
- shell - 从最后一个字符开始的字符串 shell 脚本中的子字符串
- web - 网站未从 www 重定向到 https
- spring-security - 永远不会调用 Spring 安全过滤器
- opencv - OpenCV 文本检测
- django - Django url前缀关联
- android - 未解决的参考:requireLensFacing | 安卓工作室
- java - 获取 Firestore 中已删除文档的 ID
- django - 重定向后Django表单不可见
- javascript - 如何在 javascript 中从 jsx 表单创建键值数组?
- reactjs - 如果之前的访问来自另一个网站,则使用 react-router 返回