9

我试图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容器中的 。在 myhandleLogin中,我的this值是undefined。我已经尝试绑定this到中的函数constructor,但它仍然是undefined

此外,当我在render函数中放置断点时,我有一个this.context.router,但它是undefined. 我怎样才能得到我的this正确,handleLogin以及如何确保我有我routercontext,但它不是undefined

4

2 回答 2

11

跟上变化的最佳方式是查看发布页面。

在 和 的 React Router 版本中> 1.0.0-beta3< 2.0.0-rc2没有context.router. 相反,您需要寻找context.history.

如果您使用版本<= 1.0.0-beta3>= 2.0.0-rc2context.router则存在。简而言之,发生的事情是它被删除了,history但随后维护人员决定最好将历史库 API 隐藏在路由器后面,因此他们router在 2.0 RC2 及更高版本中带回了上下文。

于 2015-10-03T13:32:12.507 回答
1

我有同样的问题,我想从需要身份验证打开的组件重定向到登录页面。

我用 this.context.router.push('/login')它对我不起作用。

我们可以通过 props 到达路径,所以我对它进行了编码,this.props.history.push('./login')因为我使用的是 redux store,它会更新 props 中的路径并重定向到主页。

componentWillMount() {
        if(!this.props.isAuthenticated){
            // redirect
            this.props.history.push('/login');
        }
    }

当组件打开时(由高阶组件包装),它将检查用户是否经过身份验证。如果未通过身份验证,它将重定向到主页。

于 2019-06-04T10:49:48.047 回答