首页 > 解决方案 > this.props.history.push 在刷新后工作

问题描述

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

我有一个对话框(AjouterDisponibilite),我用组件议程上的 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

我该如何解决?

标签: javascriptreactjsreact-router-domrefreact-ref

解决方案


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

带有refprop 的组件在挂载时将自己分配给 prop 的值(或以自身作为参数调用函数),并且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;
    }
}

推荐阅读