javascript - react-router "Cannot read property ' push' of undefined"

标签 javascript reactjs react-router react-router-component

我对 React 和 React-router 很陌生。

react 的问题在于,在我的应用程序的某些页面上,react-router 正在运行,但有些页面会出现这样的错误:“无法读取未定义的属性‘push’”。

我正在使用 React 0.14.1

我的路由代码如下所示:

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'));

我的组件现在是这样的:

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');
    }
  }

}

谁能帮我解决这个问题?谢谢。

最佳答案

直接从 react-router 使用 hashHistory 当然是一种选择,但它会使单元测试更加痛苦。 浏览器历史记录在运行的上下文测试中通常不可用,并且模拟一个 prop 比模拟一个全局 API 更容易。

考虑使用 react-router 提供的 withRouter 高阶组件(自 v2.4.0 起)。

import { withRouter } from 'react-router';

class App extends Component {

    (...)

}

export default withRouter(App);

您的 App 类将通过 props 接收 router 并且您可以安全地执行 this.props.router.push('/'); .

关于javascript - react-router "Cannot read property ' push' of undefined",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39184049/

相关文章:

javascript - CSS/JS 删除(自动)换行符/文本换行前的空格

javascript - 根据参数为成员分配角色

javascript - Jest 快照 @import CSS 失败

reactjs - 带有react-router-dom的路由在父容器中打开

reactjs - 访问react-router动态段时崩溃

reactjs - React 应用程序登录错误 : Maximum update depth exceeded

javascript - PHP如何选择并读取csv文件内容而不上传

javascript - 如何使用 Material UI 表分页在每页显示正确的行

node.js - bcrypt,续集错误在 ../node_modules/node-pre-gyp/lib/publish.js 找不到模块 : Error: Can't resolve 'aws-sdk'

javascript - 从具有特定字符的字符串中提取子字符串