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.
Your app does not have an instance of Router in its props which is giving you Cannot read property 'push' of undefined
.
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
import { hashHistory } from 'react-router;'
...
hashHistory.push('/');
in your componentWillMount
lifecycle event.
The docs are here
Hope this helps!