繁体   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