2015-10-19 74 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