2015-09-26 51 views
7

我正試圖從我的組件中訪問我的router,它是未定義的。這裏是我的router爲什麼我的反應組件中的context.router未定義?

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

這裏是容器:

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

最後組件:

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; 

當我點擊login按鈕,它擊中的的handleLogin容器。在我的handleLogin中,我的this值是undefined。我試圖將this綁定到constructor中的函數,但它仍然是undefined

此外,當我在我的render函數中放置斷點時,我有一個this.context.router,但它是undefined。我如何在我的handleLogin中獲得我的this正確,以及如何確保我的在context上,而不是undefined

回答

10

跟上更改的最佳方式是查看Releases頁面。

在React路由器版本是> 1.0.0-beta3< 2.0.0-rc2,沒有context.router。相反,你需要尋找context.history

如果您使用版本<= 1.0.0-beta3>= 2.0.0-rc2,那麼context.router就在那裏。簡而言之,它發生了什麼,它被刪除了,以支持history,但維護人員決定最好將歷史庫API隱藏在路由器後面,以便在2.0 RC2及之後的版本中回溯router環境。

+2

我有一個預感,這個建議是過時的。我正在使用react-router版本2.0.0-rc5,並且我收到警告,表明情況正好相反。它促使我使用context.router而不是context.history。你能否介紹一下這方面的情況?謝謝! – Ryan

+1

@Ryan有同樣的感覺,並可以驗證'context.history'已被棄用。 'context.router'是首選。對我來說,我只需在'contextTypes'中用'router'替換'history'。 – sighrobot

+0

@sighrobot謝謝,我更新了答案。 –