[英]Scoping during Login with React and react-redux-firebase
我正在使用react-redux-firebase进行身份验证和用户管理。一旦用户登录,我想将用户导航到他们的仪表板,其网址为“dahboard / userId”。 当用户验证firebase时,我们会在那里给出一个具有用户ID的响应。 问题是当我尝试通过'this.history.push('dahsboard / uid')完成导航请求时,我不断收到错误消息,指出'this'未定义。 我很确定这是一个范围问题,但我无法弄清楚我需要如何构建代码来解决问题。
我已经尝试将uid存储为const。 我还尝试将另一个异步函数链接到请求。 this.props未定义或uid未定义。
onSubmit = (e) => {
e.preventDefault();
// this.props.signIn(this.state);
this.props.firebase.login(this.state)
.then(function(res){
const userId = res.user.user.uid;
console.log(userId);
this.props.push('/dashboard/userId');
// ! Scoping issue - How to get 'props' in or userId out of this scope
})
.catch(
err => console.log(err.message),
)
}
render() {
const authError = this.props.authError;
return(
<div className="container">
<div className="row">
<div className="col-sm-9 col-md-7 col-lg-5 mx-auto">
<div className="card card-signin my-5">
<div className="card-body">
<div className = "red-text center">
{authError ? <p> {authError.message} </p> : null}
</div>
<h5 className="card-title text-center">Sign In</h5>
<form className="form-signin" onSubmit={this.onSubmit}>
<div className="form-label-group">
<label>Email address
<input type="email" id="inputEmail" className="form-control" placeholder="Email address" value={this.state.email} onChange={this.onChangeEmail} required autoFocus />
</label>
</div>
<div className="form-label-group">
<label>Password
<input type="password" id="inputPassword" className="form-control" placeholder="Password"
value={this.state.password}
onChange={this.onChangePassword}
required />
</label>
</div>
<div className="custom-control custom-checkbox mb-3">
<input type="checkbox" className="custom-control-input" id="customCheck1" />
<label className="custom-control-label" >Remember password
</label>
</div>
<button className="btn btn-lg btn-primary btn-block text-uppercase" type="submit">Sign in</button>
<hr className="my-4" />
</form>
</div>
</div>
</div>
</div>
</div>
)
}
}
export default compose(
//map firebase redux to props
firebaseConnect((props) => {
}),
connect(
//map redux-state to props
(state) => ({
userId: state.firebase.auth.uid,
authError: state.firebase.authError,
auth: state.firebase.auth
})
)
)(Login)
您需要使用来自“react-router”的withRouter,如下所示:
export default withRouter(connect(mapStateToProps, {
...
})(App));
然后它将通过this.props访问;
如果你有一个嵌套组件,你也可以通过App中的道具传递history
:
<NestedComponent history={this.props.history}/>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.