如果用户之前已经登录并且该信息已保存,则我试图更改组件中的路由。我看到setState
方法中正在调用componentDidMount
,但是render
方法没有被再次调用,而不是在用户中“登录”。
如果我登录用户,将调用loggedIn()
并以正确的状态集重新呈现该组件。
根据ReactJS文档,我可以立即在setState
中调用componentDidMount
,但是它似乎无法使用正确的状态进行渲染。任何帮助将不胜感激
import * as React from 'react';
import { Route, Redirect, withRouter, RouteComponentProps } from 'react-router-dom';
import SignIn from '../components/signIn/signInComponent';
import Register from '../components/register/registerComponent';
import Dashboard from '../components/dashboard/dashboard.component';
interface AuthState {
isAuthenticated: boolean
}
class Routes extends React.Component<any, AuthState>{
constructor(props: any) {
super(props);
this.state = {
isAuthenticated: false
};
}
componentDidMount = () => {
this.setState({
isAuthenticated: true
});
}
loggedIn = () => {
this.setState({
isAuthenticated: true
});
}
render() {
return (
<div>
<Route path='/' exact render={() => (
!this.state.isAuthenticated ? (<Redirect to='/signin'/>) : (<Dashboard/>)
)}/>
<Route path='/signin' exact render={() => (
<SignIn onLoggedIn={this.loggedIn}/>
)}/>
<Route path='/register' exact component={Register}/>
</div>
);
}
}
export default withRouter(Routes);