小编典典

为什么我的react组件中的context.router没有定义?

reactjs

我正在尝试router从我的组件中访问我的文件,它是未定义的。这是我的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。如何让我的this在我的正确handleLogin,以及如何我确保我有我routercontext,这是不是undefined


阅读 348

收藏
2020-07-22

共1个答案

小编典典

保持更改的最佳方法是浏览“ 发行”页面。

在阵营是路由器版本> 1.0.0-beta3< 2.0.0-rc2,没有context.router。相反,您需要寻找context.history

如果使用版本<= 1.0.0-beta3>= 2.0.0-rc2,则context.router在那里。简而言之,发生了什么事,它被删除而取而代之,history但是随后维护人员决定最好将History
Library API隐藏在路由器后面,因此他们router在2.0 RC2及更高版本中使用了上下文。

2020-07-22