简体   繁体   中英

Updating State of type Array<Object> in ReactJS without mutation

I have an array of objects with meta information. Here is the schema for a object.

       this.state.slotData [{
        availability: boolean,
        id: number,
        car: {
            RegistrationNumber : string,
            Color: string
        }, {...}, {...}, ...]

Now, for any incoming car, I record car details I am further checking if any slots are available, and if so, updating the slotData state. I filter() the slotData to find all available slots then refer availableSlots[0] to access the id of the nearest empty slot. Now, I just have to update this.state.slotData without mutating it.

If you want to apply immutable update and add car as a single object in slotData array you should first spread whole slotData array and than add car object like this:

const updatedSlotData = [...slotData, carObj];
this.setState({ slotData: updatedSlotData });

As long as you make a copy first, you can safely mutate the copy.

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