2015-09-26 56 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谢谢,我更新了答案。 –