reactjs – 为什么我的context.router在我的react组件中未定义?

我试图从我的组件内访问我的路由器,它是未定义的.这是我的路由器:
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;

当我点击登录按钮时,它会点击容器中的handleLogin.在我的handleLogin中,我的这个值是未定义的.我试图将它绑定到构造函数中的函数,但它仍然是未定义的.

另外,当我在我的渲染函数中放置一个断点时,我有一个this.context.router,但它是未定义的.如何在我的handleLogin中获得正确的结果以及如何确保我的路由器在上下文中并且未定义?

跟上变化的最佳方法是浏览 Releases页面.

在>的React Router版本中. 1.0.0-beta3和< 2.0.0-rc2,没有context.router.相反,你需要寻找context.history. 如果您使用版本< = 1.0.0-beta3或> = 2.0.0-rc2,那么context.router就在那里.简而言之,发生的事情是它被删除而有利于历史,但后来维护人员决定最好隐藏路由器后面的历史库API,因此他们将在2.0 RC2及以后的路由器上下文.

相关文章

react 中的高阶组件主要是对于 hooks 之前的类组件来说的,如...
我们上一节了解了组件的更新机制,但是只是停留在表层上,例...
我们上一节了解了 react 的虚拟 dom 的格式,如何把虚拟 dom...
react 本身提供了克隆组件的方法,但是平时开发中可能很少使...
mobx 是一个简单可扩展的状态管理库,中文官网链接。小编在接...
我们在平常的开发中不可避免的会有很多列表渲染逻辑,在 pc ...