javascript - 未捕获( promise 中)TypeError : _this2. context.router.push 不是函数

标签 javascript reactjs redirect react-router

我尝试在单击提交按钮后重定向我的页面,为此,我的 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 })
      );
    }
  }

还有我的propTypescontextTypes

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”选项卡查看我所说的内容。

enter image description here

关于javascript - 未捕获( promise 中)TypeError : _this2. context.router.push 不是函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43368865/

相关文章:

jq 输出的重定向

javascript - 在 cordova 应用程序中找不到插件

javascript - 如何在选项标签内添加标签?

javascript - 如何使用 JQuery 将动态创建的表中的值传递到新的数据库查询中?

javascript - 对多个输入 onChange 事件使用单个处理程序

node.js - 重定向响应中的 cookie

javascript - 通过 javascript 或 HTML 5 的 Kerberos

javascript - 如何在reactJS中的setState中传递.JSON

javascript - react Hook : How to read & update state in hooks without infinite loops with react-hooks/exhaustive-deps rule

.htaccess 将所有其他浏览器语言重定向到默认语言