Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
259 views
in Technique[技术] by (71.8m points)

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

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".

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Using hashHistory directly from react-router is certainly an option, but it makes unit-testing a bit more painful. Browser history will generally not be available in the context tests run in and it's easier to mock out a prop than to mock out a global API.

Consider using the withRouter higher-order-component that react-router provide (since v2.4.0).

import { withRouter } from 'react-router';

class App extends Component {

    (...)

}

export default withRouter(App);

Your App class will receiver router via props and you can safely do this.props.router.push('/');.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...