Routing problem: this.context.router is not detected when trying to redirect

I am trying to automatically change the path after n seconds. (without use <Link to="/home">Home</Link>).

My code is as follows:

class ComponentName extends Component {
  constructor (props, context) {
    super(props, context);
  }
  componentDidMount () {
    setTimeout(function(){
      this.context.router.transitionTo('/home');
    }.bind(this), 3000)
  }
  render() {return (<div>..will go to the home page</div>)}
}

ComponentName.contextTypes = {
  router: function () { 
    return React.PropTypes.func.isRequired;
  }
};
export default ComponentName;

This is the error I get

Uncaught TypeError: Cannot read property 'transitionTo' of undefined on line this.context.router.transitionTo('/home');aka this.context.router undefined.

this.context is defined, so there is no problem afaik.

That I tried some of the following:

In the constructor:
this.context = context;

In the class:
static contextTypes: {
  history: React.PropTypes.object,
  location: React.PropTypes.object,
  router: React.PropTypes.func.isRequired
}

Before exporting (with and without function):
ComponentName.contextTypes = {
  router: React.PropTypes.func.isRequired
}

I also tried changing the route to the story or just calling a function in context:
this.context.history.transitionTo('/home');
this.context.transitionTo('/home');
this.transitionTo('/home');

, this.context.router - undefined, ( : https://github.com/rackt/react-router/issues/975) -, .

. ES6

"react": "^0.14.0",
"react-router": "^1.0.0-rc3"
+4
1

:

import createHistory from 'history/createHashHistory'

export default createHistory()

, , :

import React from 'react'
import { Provider } from 'react-redux'
import { Router } from 'react-router-dom'

import history from '../history'

const Application = (props) => {
  return (
    <Provider store={props.store}>
      <Router history={history}>
        ...
      </Router> 
    </Provider>
  )
}

, , , , , . . .

-1

Source: https://habr.com/ru/post/1612246/


All Articles