我有一个 PrivateRoute 来验证令牌是否有效并且它是一个异步函数。问题是:我的渲染视图验证不起作用,它总是渲染:
应用程序.js
const PrivateRoute = ({ component: Component, ...rest }) => (
<Route
{...rest}
render={props =>
isAuthenticated() ? (
<Component {...props} />
) : (
<Redirect to={{ pathname: "/", state: { from: props.location } }} />
)
}
/>
);
const Routes = () => (
<BrowserRouter>
<Fragment>
<Switch>
<Route exact path="/" component={SignIn} />
<PrivateRoute path="/app" component={App} />
</Switch>
<ModalContainer />
</Fragment>
</BrowserRouter>
);
export default Routes;
身份验证.js
import axios from 'axios'
export const isAuthenticated = async () => {
const isValidRequest = false;
const resp = await axios.get('http://127.0.0.1:8080...')
data = resp.data;
console.log(data);
....// more code
return isValidRequest;
}
如何确保 PrivateRoute 将等待功能isAuthenticated()
?
更新1:
const Routes = () => {
const [state, setState] = useState({isLoading: true, authenticated: false});
useEffect(() => {
async function checkAuth() {
const isAuth = await isAuthenticated();
setState({isLoading: false, authenticated: isAuth});
}
}, []);
if(state.isLoading) {
return <div>Loading....</div>
}
return (
<BrowserRouter>
<Fragment>
<Switch>
<Route exact path="/" component={SignIn} />
<PrivateRoute path="/app" isAuthenticated={state.authenticated} component={App} />
</Switch>
<ModalContainer />
</Fragment>
</BrowserRouter>
);
}