我从服务器收到有关身份验证当前用户的响应。基于此信息,我正在渲染HomePage或LoginPage。如何将所有未经授权的用户重定向到“ /登录” URL,将其他用户重定向到主页。当我使用history.push('/ login')时,它会保存URL中的内容,因为在第一次渲染时,身份验证状态始终为false
class App extends React.Component {
componentDidMount() {
this.props.getAuthStatusThunk();
//here need some control for url, but it doesn`t work
}
render() {
let { component: Component, path } = this.props;
return (
<Route path={path} render={() => {
if (!this.props.isAuth) {
return <LoginPageContainerLoader />;
}
return <MainPage />
}} />
);
}
}
您也可以在loading
中保留error
和state
值。然后检查状态值中的任何一个是否为set
或not
。基于状态值,相应地导航用户。
您可以在调用isCheckingLogin
时将状态getAuthStatusThunk
设置为true。在这里,我包括一个用于实现它的示例代码段。
class App extends React.Component {
constructor() {
super()
this.state = { isCheckingLogin: false }
this.getAuthStatusThunk = this.getAuthStatusThunk.bind(this)
}
componentDidMount() {
getAuthStatusThunk()
}
async getAuthStatusThunk() {
this.setState({ isCheckingLogin: true })
let res = await (checkIsLoggedIn())
if (res.isLoggedIn) {
this.setState({ isCheckingLogin: false })
}
else {
this.props.history.push('/login')
this.setState({ isCheckingLogin: false })
}
}
render() {
return (
<React.Fragment>
{isCheckingLogin ? <Loader /> : <MainPage />}
</React.Fragment>
)
}
}
Loader
组件可用于在显示登录状态时显示微调器或某种动画,如果需要的话。