【问题标题】:this.props.history.push is working just after refreshthis.props.history.push 在刷新后工作
【发布时间】:2019-09-24 20:31:05
【问题描述】:

我有一个 react-big-calendar,当我点击它时,它有一个按钮,他的模式会出现,我还有一个日历图标按钮,可以将我重定向到另一个 URL /planning。

我有一个对话框 (AjouterDisponibilite),我使用组件 Agenda 上的 ref 调用它。

日历图标有一个onClick 我尝试的事件:

this.props.history.push('/planning'); 

但是当我运行它并点击图标时,URL 是正确的,但我得到一个error,如下所示:

TypeError: Cannot read property 'handleAjouter' of nullCan't perform a React state update on an unmounted component. This is a no-op, but it indicates a memory leak in your application. To fix, cancel all subscriptions and asynchronous tasks in the componentWillUnmount method

刷新此页面后,它就可以工作了。

我的代码是:https://codesandbox.io/s/xw01v53oz

我该如何解决?

【问题讨论】:

  • Props 在 React 中是不可变的。不要那样改变它们。如果您想保留数据以供在组件中使用,请使用状态,或者当然,从父级传递下来。
  • @rrd 请问我该如何解决?你能检查我的沙箱吗?
  • 在这种情况下,变异道具不是问题。 this.props.history 指向 react-router 历史对象,调用 push 是使用 react-router 重定向的推荐方法之一。更多详情:reacttraining.com/react-router/web/api/history
  • 哪个文件/行会抛出错误?该错误意味着您尝试更新未安装组件的状态。这首先不是路由问题。
  • 还没用过ref。您可以改进指向ref 问题的问题。 :-)

标签: javascript reactjs react-router-dom ref react-ref


【解决方案1】:

问题在于对 Refs 的不当使用。 Refs 旨在保留对 DOM 元素和组件实例的引用,而不是它们的函数。

带有ref 属性的组件在挂载时会将自己分配给该属性的值(或以自身作为参数调用函数),并且当它们被挂载时,它们将对null 引用执行相同的操作已卸载。

有了这些知识,你必须改变你的Agenda组件的代码如下:

ModalAjout = (ref) => {
    if (ref) {
        this.ajout = ref.handleAjouter;
    } else {
        this.ajout = null;
    }
}

ModalAjoutb = (ref) => {
    if (ref) {
        this.ajoutb = ref.handleAjouter;
    } else {
        this.ajoutb = null;
    }
}

【讨论】:

  • 我用<AjouterDisponibilite ref={(evt) => this.ModalAjout({evt})}/> 调用他的组件?
  • 我试过了,但它不起作用你能检查一下吗? codesandbox.io/s/xw01v53oz
  • 不,你不调用它,你只需像以前一样将它传递给 prop ref={this.ModalAjout}
  • 你能检查一下我的沙箱吗? codesandbox.io/s/xw01v53oz我试试你说的,还是不行。
  • 您现在遇到的错误是由于 AjouterDisponibilite 组件中未定义的状态变量,与此处提出的问题无关。但因为它是一个快速的解决方案:tranchesC 未在您的州定义。你应该把onClick={this.ajoutb}改成onClick={() => this.ajoutb()}
【解决方案2】:

解决此问题的最佳方法是添加以下代码:

history.pushState(null, document.title, location.href);

在做什么?它在第一次加载后使用一个值初始化历史记录,然后您不需要进行刷新。

就我而言,我是在开发 Android 应用程序时这样做的,并且有一些我想用后退按钮关闭的模式以提供更原生的体验。

【讨论】:

    【解决方案3】:

    我修复它,添加:

    <AjouterDisponibilite ref={(evt) => this.ModalAjout({evt})} start={this.state.startDisponibilite} end={this.state.endDisponibilite} date={this.state.dateDisponibilite}/>
    <AjouterDisponibilite ref={(evt) => this.ModalAjoutb({evt})} />
    

    方法ModalAjout必须有参数。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-10-09
      • 2017-11-02
      • 2017-01-19
      • 2013-12-12
      • 1970-01-01
      • 2019-09-16
      • 2015-01-24
      • 1970-01-01
      相关资源
      最近更新 更多