我尝试在单击提交按钮后重定向我的页面,为此,我的 onSubmit 方法如下所示;
onSubmit(e){
e.preventDefault();
if (this.isValid()){
this.setState({ errors: {}, isLoading: true });
this.props.userSignupRequest(this.state).then(
() => {
this.context.router.push('/');
},
( data ) => this.setState({ errors: data.response.data, isLoading: false })
);
}
}
还有我的propTypes和contextTypes;
SignupForm.propTypes = {
userSignupRequest: React.PropTypes.func.isRequired
}
SignupForm.contextTypes = {
router: React.PropTypes.object.isRequired
}
我不知道为什么,但它一直显示错误并且不重定向。 我还尝试了 browserHistory.push('/') 但它也不起作用。
我犯的错误是;
Uncaught (in promise) TypeError: _this2.context.router.push is not a function
at props.userSignupRequest.then._this2.setState.errors
正如我所说,我也尝试过browserHistory;
import { browserHistory } from 'react-router';
和onSubmit方法;
onSubmit(e){
e.preventDefault();
if (this.isValid()){
this.setState({ errors: {}, isLoading: true });
this.props.userSignupRequest(this.state).then(
() => {
browserHistory.push('/');
},
( data ) => this.setState({ errors: data.response.data, isLoading: false })
);
}
}
我的路由器也是这样;
const router = (<Provider store={store}>
<Router history={browserHistory}>{routes}</Router>
</Provider>);
它抛出的错误与另一个错误相同。
Uncaught (in promise) TypeError: Cannot read property 'push' of undefined
at props.userSignupRequest.then._this2.setState.errors
如果需要更多内容,请在下面添加,我将编辑我的帖子。
谢谢。
最佳答案
我通过更改下面的代码解决了这个问题。
this.context.router.push('/');
在react-router 4.0.0以上版本中,这个push方法移到了“history”方法下面,新版本看起来像这样;
this.context.router.history.push('/');
这工作正常并解决了我的问题。
注意
您可以通过浏览器的“React”选项卡查看我所说的内容。
关于javascript - 未捕获( promise 中)TypeError : _this2. context.router.push 不是函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43368865/