小编San*_*nda的帖子

路由问题:尝试重新路由时未定义 this.context.router

我试图在 n 秒后自动更改路径。(不使用<Link to="/home">Home</Link>)。

我的代码如下所示:

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;
Run Code Online (Sandbox Code Playgroud)

这是我得到的错误

Uncaught TypeError: Cannot read property 'transitionTo' of undefined 在线this.context.router.transitionTo('/home');又名 this.context.router 是未定义的。

this.context 已定义,因此没有问题。

我尝试了以下一些方法:

  • 在构造函数中:
  • this.context = context;
    
    Run Code Online (Sandbox Code Playgroud)

  • 在课堂里:
  • static contextTypes: {
      history: React.PropTypes.object,
      location: …
    Run Code Online (Sandbox Code Playgroud)

    javascript reactjs react-router

    5
    推荐指数
    1
    解决办法
    2508
    查看次数

    标签 统计

    javascript ×1

    react-router ×1

    reactjs ×1