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

jha*_*amm 9 reactjs redux

我试图router从我的组件中访问我,它是未定义的.这是我的router:

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

这是容器:

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);
Run Code Online (Sandbox Code Playgroud)

最后组件:

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;
Run Code Online (Sandbox Code Playgroud)

当我点击login按钮时,它会点击handleLogin容器中的内容.在我handleLogin,我的this价值是undefined.我试图绑定this到该函数constructor,但它仍然是undefined.

另外,当我在我的render函数中放置一个断点时,我有一个this.context.router,但确实如此undefined.我怎样才能弄清楚我的this正确性handleLogin以及如何确保我拥有自己router的权利context而不是undefined

Dan*_*mov 11

跟上变化的最佳方法是查看" 版本"页面.

在反射路由器版本中,> 1.0.0-beta3并且< 2.0.0-rc2没有context.router.相反,你需要寻找context.history.

如果您使用版本<= 1.0.0-beta3>= 2.0.0-rc2,context.router那就在那里.简而言之,发生的事情是它被删除了支持history但是后来维护人员决定最好隐藏路由器后面的历史库API,所以他们回到router2.0 RC2及以后的上下文.

  • 我有预感这个建议已经过时了.我正在使用react-router版本2.0.0-rc5,我收到警告,表明相反的情况属实.它促使我使用context.router而不是context.history.你能否对此有所了解?谢谢! (2认同)