簡體   English   中英

this.props.history.push剛剛刷新后正在運行

[英]this.props.history.push is working just after refresh

我有一個反應大日歷,當我點擊它時有一個按鈕,他的模態會出現,我還有一個日歷圖標按鈕,它將我重定向到另一個URL /計划。

我有一個對話框(AjouterDisponibilite),我用我的組件議程中的ref調用它。

日歷圖標有一個onClick事件,我嘗試:

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

但當我運行它並點擊圖標時,URL指向正確,但我收到error ,如下所示:

TypeError: Cannot read property 'handleAjouter' of null並且Can'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 Can'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

我該如何解決?

問題是Refs的使用不當。 Refs旨在保留對DOM元素和組件實例的引用,而不是它們的功能。

具有ref prop的組件將在裝入時將自己分配給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;
    }
}

解決此問題的最佳方法是添加以下代碼:

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

在做什么? 它是在第一次加載后用一個值初始化歷史記錄,然后您不需要進行刷新。

在我的情況下,我在開發Android應用程序時做了這個,並且我想用后退按鈕關閉一些模態以提供更原生的體驗。

我修正了它,添加:

<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方法必須有一個參數。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM