react-router"无法读取未定义的“推送”属性 [英] react-router " Cannot read property 'push' of undefined"

查看:133
本文介绍了react-router"无法读取未定义的“推送”属性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我很反应和反应路由器。

i am quite new to react and react-router.

反应问题在于,在我的应用程序的某些页面上,路由器工作正在运行像这样的错误:无法读取未定义的属性'推送'。

Problem with react is here that, on some pages of my application react-router is working and some giving error like this: "Cannot read property 'push' of undefined".

我正在使用react 0.14.1

i am using react 0.14.1

我的路由代码如下所示:

My routing code looks like this:

render(
<Router history={hashHistory}>
  <Route path="/" component={Loginpanel}/>
  <Route path="Index" component={Index}/>
  <Route path="Form" component={Form} />
  <Route path="Checkindex" component={Index}/>

  <Route path="Signup" component={Signup}/>
  <Route path="Admin" component={Admin}/>
  <Route path="AdminEditDetails" component={AdminEditDetails}/>
  <Route path="AdminDetails" component={AdminDetails}/>


</Router>,
document.getElementById('js-main'));

我的组件现在是这样的:

My component is like this now:

class  App extends React.Component {

  constructor(props) {
    super(props);
    this.state= {      
      comments: AppStore.getAll();
    };
  }

  componentWillMount() {  
    var length = this.state.comments.length;
    var firstnumber = length - 4;

    if(length == 0){
      console.log("here comes");
      this.props.router.push('/');
    }
    else{
      console.log('work normally');
    }
  }

}

任何人都可以帮我这个?谢谢。

Can anyone help me with this? Thanks.

推荐答案

你的应用在其道具中没有路由器的实例,它给你不能读取未定义的属性'push'

Your app does not have an instance of Router in its props which is giving you Cannot read property 'push' of undefined.

我假设您正在导入withRouter以获取路由器的实例,因此您需要如果您仍想使用该组件,则需要将组件包装在其中...(例如这里但没有建议)

I'm assuming you're importing withRouter to get the instance of the Router so you'd need to wrap the component in that if you still want to use that... (example here but not suggested)

相反,更好的编程导航方法是使用

Instead, a better approach to programmatically navigating is to use

从'react-router;'导入{hashHistory}'
...
hashHistory.push('/');
componentWillMount 生命周期事件中。

文档是这里

希望这会有所帮助!

这篇关于react-router&quot;无法读取未定义的“推送”属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆