2015-10-19 105 views
4

我试图自动在n秒后更改路径。 (不使用<Link to="/home">Home</Link>)。路由问题:尝试重新路由时未定义this.context.router

我的代码如下所示:

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.context.router.transitionTo('/home');越来越

Uncaught TypeError: Cannot read property 'transitionTo' of undefined 又名this.context.router是不确定的错误。

this.context被定义,所以没有问题那里afaik。

事情我已经尝试了以下一些:

  • 在构造函数中:
  • this.context = context; 
    

  • 在类:
  • static contextTypes: { 
        history: React.PropTypes.object, 
        location: React.PropTypes.object, 
        router: React.PropTypes.func.isRequired 
    } 
    

  • 出口(试图与前&无功能):
  • ComponentName.contextTypes = { 
        router: React.PropTypes.func.isRequired 
    } 
    

  • 我也试着改变路线的历史,或只调用上下文的功能:
  • this.context.history.transitionTo('/home'); 
    this.context.transitionTo('/home'); 
    this.transitionTo('/home'); 
    

    事实是,this.context.router仍然是不确定的,我已经搜索更多的线程(主要是这一个:https://github.com/rackt/react-router/issues/975)在这一点上,仍然无法找到适合我的东西。

    注:我使用ES6 &

    "react": "^0.14.0", 
    "react-router": "^1.0.0-rc3" 
    

    回答

    -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> 
    ) 
    } 
    

    然后最后,当你需要访问历史记录我n您的任何组件,只需从您导出的相同文件中导入即可推送下一个路由。看到这篇文章here欲知更多信息。

    +0

    为什么downvote?这工作 – Dude