Why is my context.router undefined in my responsive component?

I am trying to access my router from my component and undefined. Here is my router :

 React.render( <Provider store={store}> {() => <Router> <Route path="/" component={LoginContainer} /> </Router> } </Provider>, document.getElementById('app') ); 

Here is the container:

 class LoginContainer extends React.Component { constructor() { super(); } static propTypes = { handleLogin: PropTypes.func.isRequired } static contextTypes = { router: React.PropTypes.object } handleLogin() { this.props.dispatch(Actions.login(null, null, this.context.router)); } render() { return ( <Login auth={this.props} handleLogin={this.handleLogin} /> ); } } function mapStateToProps(state) { return { stuff: [] } } export default connect(mapStateToProps)(LoginContainer); 

And finally, the component:

 import React, { PropTypes } from 'react'; class Login extends React.Component { static propType = { handleLogin: PropTypes.func.isRequired } static contextTypes = { router: React.PropTypes.object } render() { return ( <div className="flex-container-center"> <form> <div className="form-group"> <button type="button" onClick={this.props.handleLogin}>Log in</button> </div> </form> </div> ); } } module.exports = Login; 

When I click the login button, it gets into handleLogin in the container. In my handleLogin , this undefined . I tried to associate this with a function in constructor , but it is still undefined .

Also, when I set a breakpoint in my render function, I have this.context.router , but it is undefined . How can I get the correct this in my handleLogin and how can I make sure that I have a router on context and that is not undefined ?

+7
reactjs redux
source share
2 answers

The best way to keep up with the changes is to look at the Releases page.

In versions of React Router that are > 1.0.0-beta3 and < 2.0.0-rc2 , there is no context.router . Instead, you need to look for context.history .

If you are using versions <= 1.0.0-beta3 or >= 2.0.0-rc2 , context.router is located there. In short, it happened that it was deleted in favor of history , but then the developers decided to hide the history library API behind the router, so they will return the router context to 2.0 RC2 and beyond.

+10
source share

I had the same problem, I want to redirect to the login page from a component that requires authentication to open.

I used this.context.router.push('/login') it did not work for me.

We can get to the path through the details, so I encoded it this.props.history.push('./login') since I work with redundant storage, it will update the path in the details and redirect to the home page.

 componentWillMount() { if(!this.props.isAuthenticated){ // redirect this.props.history.push('/login'); } } 

when a component is open (wrapped in a high-order component), it will check if the user is authenticated. If it is not authenticated, it will be redirected to the home page.

0
source share

All Articles