简体   繁体   English

更新数组类型的状态 <Object> 在ReactJS中没有突变

[英]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. 现在,对于任何传入的汽车,我都会记录汽车详细信息,然后进一步检查是否有可用的插槽,如果有,则更新slotData状态。 I filter() the slotData to find all available slots then refer availableSlots[0] to access the id of the nearest empty slot. filter() slotData查找所有可用的插槽,然后引用availableSlots [0]访问最近的空插槽的ID。 Now, I just have to update this.state.slotData without mutating it. 现在,我只需要更新this.state.slotData而不对其进行更改

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: 如果要应用不可变的更新并将car作为单个对象添加到slotData数组中,则应首先散布整个slotData数组,然后再添加car对象,如下所示:

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

As long as you make a copy first, you can safely mutate the copy. 只要先制作副本,就可以安全地对副本进行突变。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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