簡體   English   中英

如何強制更新(重新渲染)React 組件?

[英]How to forceUpdate (re-render) React components?

我正在開發一個控件,它將累積值更新到轉發月份。

我的更新 state 的函數是在輸入元素的“onChange”事件上觸發的。 我的期望是,由於 state 已發生變異,它應該立即觸發重新渲染 - 但它沒有。

當我將焦點移到其他控件上或折疊 GroupList 時,會發生重新渲染。

下面是我如何更新 state 的代碼。

public handlerUpdatedAmount(elementId: string, sourcePeriod: ICellDynamicsMeta) {

        let newItems: IRecords[] = this.updateMonthlyAndCumulativeItems(this.state.items, elementId, sourcePeriod);

        this.setState({ items: newItems });

        //this.forceUpdate(); //Tried this option as well, but it does not update as well.
    }

見下面兩行代碼:

...
let newItems: IRecords[] = this.updateMonthlyAndCumulativeItems(this.state.items, elementId, sourcePeriod);

this.setState({ items: newItems });
...

您將this.state.items作為參數傳遞給 function updateMonthlyAndCumulativeItems The only possible issue in your code is that you are mutating the state in updateMonthlyAndCumulativeItems function and then setting the same state in the next line and there fore react thinks that the state has not changed and never re-render.

不要將 this.state.items 作為參數傳遞。 updateMonthlyAndCumulativeItems function 已經可以訪問 state。 還要確保不要直接改變 state。

您在 JavaScript 中遇到了 arrays 的深度克隆與淺克隆的問題。

基本上useState上的 useState 跟蹤對數組本身的引用,而不是數組的內容。 當您調用updateMonthly...()時,您可能會返回一個淺克隆數組。

簡單的解決方案是解構數組並將其分配給setState中新數組的內容。 就像是:

this.setState({ items: [...newItems]})

如果這不起作用,則可能是newItems中填充的內容存在問題。 您可以查看有關 react 如何根據 state 更改決定何時重新渲染的文檔。

暫無
暫無

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

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