【问题标题】:this.props.history.push not workingthis.props.history.push 不工作
【发布时间】:2017-05-02 13:25:02
【问题描述】:

当我导出一个组件时:

export default class Link extends React.Component{

  onLogout() {
    this.props.history.push('/');
  }

与此相关的按钮正确更改了 react-router v4 中的页面。

但是,在我的 main.js 文件中,我目前正在尝试获得类似的内容:

if (insert conditional here) {
    this.props.history.push('/');
  }

工作。但它只是给我一个类型错误。

'Uncaught TypeError: Cannot read property 'history' of undefined'.

我确实安装了所有正确的依赖项,并且它在我的其他组件中运行良好。我目前在主 js 文件中有这个 if 语句(它是我练习理解 v4 的一个小项目),所以我认为这可能是因为我没有扩展一个类。

有谁知道为什么相同的代码不能在主文件中运行,有没有解决方法?所有 react-router v4 的变化都让这个菜鸟感到困惑。

【问题讨论】:

  • 确保this 方法中onLogout 的上下文正确设置为类。一种方法是console.log(this.props)
  • 使用 browserHistory 代替历史记录

标签: reactjs react-router


【解决方案1】:

这意味着this.props 未定义,因为您在回调中使用this.props,而this 不是您认为的那样。要解决这个问题,请像这样使用您的回调:

<button onClick={this.onLogout.bind(this)}>

而不是

<button onClick={this.onLogout}>

你也可以这样做

import { browserHistory } from 'react-router'

... browserHistory.push('/');

编辑:关于后者,你也可以用这个包装你的组件:

import { withRouter } from 'react-router';

// in YourComponent:
... this.props.router.push('/');

export default withRouter(YourComponent);

它可能比browserHistory 更好,因为您不必指定历史类型(可以更改为hashHistory 并且仍然有效)。

【讨论】:

    【解决方案2】:

    我建议您不要将地址直接放入历史记录中,而是使用 .

    您可以将用户发送到该页面,您可以有条件地检查是否允许他查看内容,如果是,则在渲染方法中渲染返回组件,否则返回

    这会产生更简洁的代码。

    https://github.com/ReactTraining/react-router/blob/master/packages/react-router/docs/api/Redirect.md

    【讨论】:

      猜你喜欢
      • 2018-10-09
      • 2017-11-02
      • 2019-09-24
      • 1970-01-01
      • 2021-04-03
      • 2019-07-17
      • 2018-12-27
      • 2022-01-04
      • 2022-01-19
      相关资源
      最近更新 更多