反应状态 - 更新嵌套数组中对象的属性

我有一个 React 应用程序,其界面允许用户选择日期和时间段。我有一个维护状态的顶级对象,它可能如下所示:


this.state = {

  days: [{ 

    date: '12-13-2022',

    time_slots: [{

        start: '10 am',

        end: '11 am',

        selected: false

      },{

        start: '1 pm',

        end: '3 pm',

        selected: false

      }]

    }, {

    date: '12-14-2022',

    time_slots: [{

       start: '10 am',

       end: '11 am',

       selected: false

     }

  }]

}

当用户单击某个时间段时,我想将该selected属性更新为true.


到目前为止,我有这个,但我认为我正在改变状态,这是不好的做法。


slotClicked(day_index, slot_index) {

  let state = this.state.days[day_index].time_slots[slot_index].selected = true;

  this.setState({state});

}

我如何以有效的(在重新渲染方面)和不可变的方式更新状态?


元芳怎么了
浏览 145回答 3
3回答

森栏

与其他答案相反,您必须深度克隆您的阵列:slotClicked(day_index, slot_index) {  // If you prefer you can use lodash method _.cloneDeep()  const newDays = JSON.parse(JSON.stringify(this.state.days));  newDays[day_index].time_slots[slot_index].selected = true;  this.setState({days: newDays});}如果您不深度克隆您的数组,则该time_slots数组将通过引用进行复制,并且对其进行突变会改变原始数组的状态。

江户川乱折腾

您可以使用Array.map函数作为,slotClicked(day_index,slot_index){        let current_state = this.state;        this.state.days.map((days,days_index) => {            if(days_index===day_index){                // console.log("day",days);                let newSlot = '';                days.time_slots.map((time_slot,slots_index)=>{                    if(slots_index===slot_index){                        // console.log("time",time_slot);                        newSlot = Object.assign({},time_slot,{selected:true});                    }                })                // console.log("new slot",newSlot);                days.time_slots[slot_index] = newSlot;                this.setState({days:current_state},()=>{                    console.log(this.state);                });            }        });    }
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript