2 回答
TA贡献1812条经验 获得超5个赞
您将需要一些状态来保存您要查找的信息,并且您需要在效果中执行身份验证查找。
当然,您可以选择在身份验证检查进行时以某种方式显示加载指示器,但您可以根据需要找出该机制。
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
}
}
} />
}
}}
/>
);
}
TA贡献1806条经验 获得超5个赞
您可以为结果处理三种不同的状态。未定义,真实和虚假。isAuthenticated()
未定义:您的组件将显示一个加载程序,等待您的API调用结束
真/假:与你的行为相同。
只需将其存储在变量中并执行类似操作即可:
// ... Ommited code
if(isAuthed === undefined) return <Loader />;
return (
// ... Your code with true/false condition
添加回答
举报