我使用react-redux-firebase进行身份验证,用户management.Once用户登录,我希望使用url 'dahboard/userId.‘将用户导航到他们的仪表板。当用户进行身份验证时,firebase会给我们一个响应,其中包含用户的ID。问题是,当我试图通过'this.history.push('dahsboard/uid')完成一个nav请求时,我总是收到一个错误,说'this‘is undefined。我很确定这是一个作用域问题,但是我不能确切地知道我需要如何构造代码来解决这个问题。
我已经尝试将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)发布于 2019-05-14 20:33:33
您需要使用"react-router“中的withRouter,如下所示:
export default withRouter(connect(mapStateToProps, {
...
})(App));然后它将可以通过this.props访问;
如果你有一个像这样的嵌套组件,你也可以通过道具从应用程序中传递history:
<NestedComponent history={this.props.history}/>https://stackoverflow.com/questions/56130090
复制相似问题