我正在使用 React-Routerv4,当我使用登录表单登录时,我isUser
使用函数将应用组件状态值从子组件登录设置为 true,登录后setUserLogin
我可以在控制台中正确调试。我还指定了,如果我迁移到/login
路径,它会检查isUser
要迁移到的状态值,/home page
如果用户已经登录(isUser
是true
)。但是该值现在自动更改为默认值false
,当我/login
在浏览器中输入并显示登录页面而不是主页时。我是 React 的新手,所以我在这里遗漏了什么吗?这是代码片段:
import React from 'react';
import ReactDom from 'react-dom';
import 'materialize-css/bin/materialize.css'
import 'materialize-css/bin/materialize.js';
import {BrowserRouter as Router, Route , Redirect} from 'react-router-dom';
import {LoginForm} from './components/login';
import {Home} from './components/home';
import {Main} from './components/main';
import {Room} from './components/room';
import "materialize-css";
import 'materialize-css/js/toasts';
class App extends React.Component {
constructor(props){
super(props);
this.state={
isUser : false
}
this.setUserLogin = this.setUserLogin.bind(this);
}
setUserLogin(){
this.setState({isUser:true});
}
render() {
return <Router>
<div>
<Route exact path="/" component={Home}/>
<Route path="/login" render={(props)=>(
this.state.isUser ? <Redirect to="/home" /> : <LoginForm history={props.history} setUserLogin = {this.setUserLogin}/>
)} />
<Route path="/home" component={Main}/>
<Route path="/room" component={Room}/>
</div>
</Router>
};
}
ReactDom.render(<App/>, document.getElementById('app'));