简体   繁体   中英

How to forceUpdate (re-render) React components?

I'm developing a control that will update a cumulative values to the forwarding months.

My functions which update's the state is triggered on the 'onChange' event of an input element. My expectation is, since the state has been mutated, it should triggered the re-render right away – but it does not.

The re-render is happening when I move the focus on other controls or I collapse a GroupList.

Below is my code on how I update the 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.
    }

See below two lines of code:

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

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

You are passing this.state.items as a param to the 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.

Don't pass this.state.items as an argument. updateMonthlyAndCumulativeItems function already has access to the state. Also make sure not to mutate the state directly.

You're running into an issue with deep-cloning vs shallow-cloning of arrays in JavaScript.

Basically useState on arrays tracks the reference to the array itself, not the contents of the array. When you call updateMonthly...() you're probably returning a shallow cloned array.

Simple solution is to destructure the array and assign it to the contents of a new one in setState . Something like:

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

If that doesn't work than it could be an issue with what is being populated inside newItems . You can check the documentation on how react decides when to re-render based on state change.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM