2 回答

TA貢獻1812條經(jīng)驗 獲得超5個贊
您將需要一些狀態(tài)來保存您要查找的信息,并且您需要在效果中執(zhí)行身份驗證查找。
當(dāng)然,您可以選擇在身份驗證檢查進行時以某種方式顯示加載指示器,但您可以根據(jù)需要找出該機制。
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條經(jīng)驗 獲得超5個贊
您可以為結(jié)果處理三種不同的狀態(tài)。未定義,真實和虛假。isAuthenticated()
未定義:您的組件將顯示一個加載程序,等待您的API調(diào)用結(jié)束
真/假:與你的行為相同。
只需將其存儲在變量中并執(zhí)行類似操作即可:
// ... Ommited code
if(isAuthed === undefined) return <Loader />;
return (
// ... Your code with true/false condition
添加回答
舉報