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.
you can try the below code see if your
router props
is working or notalso you can visit their documentation to get more information from below url https://github.com/reactjs/react-router/blob/master/docs/guides/NavigatingOutsideOfComponents.md
You are using hashHistory. The following code should work.
The root route should also be defined.
If you are use Partial Component and calling it like
<Header />
then you should replace it by<Header {...this.props} />
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 yourcomponentWillMount
lifecycle event.The docs are here
Hope this helps!
Using
hashHistory
directly fromreact-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 thatreact-router
provide (sincev2.4.0
).Your
App
class will receiverrouter
via props and you can safely dothis.props.router.push('/');
.