【问题标题】:Uncaught (in promise) TypeError: _this2.context.router.push is not a functionUncaught (in promise) TypeError: _this2.context.router.push is not a function
【发布时间】:2017-09-08 04:40:19
【问题描述】:

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

如果还需要什么,请在下面添加,我会编辑我的帖子。

谢谢。

【问题讨论】:

  • 你使用什么版本的 react 和 react-router
  • 反应:15.5.3 反应路由器:4.0.0 @ShubhamKhatri
  • 对于 react 15.5.3 React.Proptypes is deprecated 。安装prop-types 并像import PropTypes from 'prop-types' 一样导入它并使用router: PropTypes.object.isRequired。让我知道这是否有帮助
  • 我已经在 contextTypes 的上方声明了 proptypes。没有写在我的帖子上,但如果你说,如果我声明了 propTypes 并且我已经需要安装 prop-types 也没关系,那么我会试一试。 (我编辑了我的帖子并添加了 propTypes)

标签: javascript reactjs redirect react-router


【解决方案1】:

我通过更改下面的代码解决了这个问题。

  this.context.router.push('/');

在大于等于 4.0.0 的 react-router 版本中,此推送方法移至“history”方法下方,其新版本看起来像;

  this.context.router.history.push('/');

这很好,解决了我的问题。

注意

您可以在浏览器的“React”标签中看到我在说什么。

enter image description here

【讨论】:

  • 你有构造函数吗?或者我可以看看你的代码块吗?我有同样的问题
  • 你在多大程度上有同样的问题?我的意思是,我可以分享我的构造函数,但我认为它与这个问题无关。你有什么问题?如果您在新帖子上分享有关您的问题的详细信息,也许我可以为您提供帮助。 @canperk
  • 我的问题是我有一个路由定义 App 类并且它正在工作。我还有另一个 OptionMenu 类,并且有一些链接可以导航。当我单击 时,浏览器路由正在更改,但页面 html 未更新。每次点击都会改变历史计数器。
  • 我不认为我们的问题是相同的,但您可能想将您的 标签包围在硬编码标签周围。我的意思是,你可以改变它; Home 或类似的东西。
  • 我一直在努力使用最新版本的 react 和 react-router-dom。这段代码非常适合我的问题。谢谢
猜你喜欢
  • 2017-04-13
  • 2020-03-17
  • 2020-01-06
  • 2021-03-10
  • 2021-09-30
  • 2020-12-22
  • 2019-06-15
  • 2017-07-20
  • 1970-01-01
相关资源
最近更新 更多