【发布时间】:2020-03-12 19:24:06
【问题描述】:
所以我尝试在 react laravel mix and god.. 中制作一个登录系统....太难了。现在我有了一个想法来制定正确的逻辑,这需要我将状态从一个组件传递到另一个组件。在这种情况下,我尝试将状态从 login.js 传递给 master.js 组件。
我试图通过的状态是isLogged
Login.js 代码
constructor(props){
super(props);
this.state = {userEmail: '', userPassword:'', isLogged: false, isLoggedfail: false, dataUser:{}};
this.handleChange1 = this.handleChange1.bind(this);
this.handleChange2 = this.handleChange2.bind(this);
this.handleSubmit = this.handleSubmit.bind(this);
}
handleChange1(e){
this.setState({
userEmail: e.target.value
})
}
handleChange2(e){
this.setState({
userPassword: e.target.value
})
}
handleSubmit(e){
e.preventDefault();
const usern = {
email: this.state.userEmail,
password: this.state.userPassword
}
let uri = 'http://localhost:8000/api/auth/login';
axios.post(uri, usern).then(response => {
this.setState({ isLogged: true });
this.setState({dataUser: response.data.data})
sessionStorage.setItem("key", this.state.dataUser.id_user)
console.log(this.state.dataUser.id_user)
this.props.history.push('/');
}
).catch(error => {
console.log("Error:" + error.message)
this.setState({isLoggedfail: true})
})
}
和master.js
constructor(props){
super(props);
this.state = {cari: '', diCari:false, isLoggedIn:false};
this.handleChange1 = this.handleChange1.bind(this);
this.handleSubmit = this.handleSubmit.bind(this);
}
handleChange1(e){
this.setState({
cari: e.target.value
})
}
handleSubmit(e){
this.setState({ diCari: false });
console.log("makan")
const cari = {
cari: this.state.cari
}
this.setState({ diCari: true });
this.props.history.push("/search/"+this.state.cari)
}
componentDidMount(){
if(sessionStorage.getItem("key") !== null) {
this.setState({Logged:true})
}
else{
this.setState({Logged:false})
}
}
componentDidUpdate(props){
if(this.state.logout){
this.setState({logout:false})
this.props.history.push('/')
}
else if(this.state.Logged){
if(sessionStorage.getItem("key") !== null) {
this.setState({Logged:false})
}
}
}
路线:
render(){
return(
<HashRouter>
<div className="wrap">
<Master/>
<Switch>
<Route exact path="/" component={Home} />
<Route path="/home" component={Home} />
<Route path="/login" component={Login} />
<Route path="/register" component={Register} />
<Route exact path="/search/:userId" component={Search} />
<Route exact path="/carts/:userId" component={Keranjang} />
<Route exact path="/produk/:userId" component={Product} />
</Switch>
</div>
<Footer/>
</HashRouter>
);
}
}
if (document.getElementById('app')) {
ReactDOM.render(<Index />, document.getElementById('app'));
}
请注意,我尝试在componentDidupdate 使用isLogged 状态,但现在我正在使用导致无限循环的会话检查。
非常感谢您的帮助!我被困了 3 天,使身份验证生效。
【问题讨论】:
-
你能分享你的路线吗?
-
@tareqaziz 完成兄弟
标签: javascript reactjs laravel