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

詹姆

我试图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

还有阿布拉莫夫

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

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

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

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章

React Router没有渲染

为什么即使我没有向组件传递任何内容,React仍会渲染组件?

为什么我不能在React-router 4.x中嵌套Route组件?

为什么子组件在React Native中没有从父组件接收更新的值?

React js,当我更改open的值时,为什么我的组件没有重新渲染?

为什么我的样式没有在React Native中更新?

在react-native中,为什么我无法定义组件的宽度?

为什么我的道具没有传递给子组件?

为什么我的“连接”组件中没有历史记录道具?

为什么React认为我没有在功能组件内部调用useState?

为什么没有在功能组件中获得我期望的变量,这是什么原因?

为什么我的组件模板没有显示在Vue中?

为什么我的视图没有出现在angular-ui-router中?

为什么我的 Ember 组件中的 .then() 中没有“this”上下文

为什么没有通过 react-router 中的链接收到道具

为什么我的状态在我的组件中似乎没有更新?

Vue.js:为什么我的单文件组件没有在我的模板中呈现/显示

为什么我跟踪状态历史的 React 组件没有在视觉上呈现?

为什么我的导航栏没有在 React 中呈现?

用 Enzyme 开玩笑,为什么在我的 React 组件测试中没有触发“toHaveBeenCalled”?

为什么我的功能组件没有重新渲染?

为什么我的 React 组件没有更新图片库?

为什么我的输入组件内的 setSetsValue 没有增加?

为什么我的 React Function 组件没有出现?

为什么 Bootstrap 背景和文本类没有在我的 React 组件中进行更改?

为什么 React.js 没有在新窗口中单独显示我的组件?

当我使用 setAttribute 更改属性时,为什么我的自定义组件没有更新?

我在 React 子组件中的函数的参数没有被传递给父组件的函数。为什么会这样?

为什么当 Set 状态改变时我的 React 组件没有重新渲染?