为了账号安全,请及时绑定邮箱和手机立即绑定

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

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

元芳怎么了 2021-06-15 11:14:41
我有一个 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});}我如何以有效的(在重新渲染方面)和不可变的方式更新状态?
查看完整描述

3 回答

?
森栏

TA贡献1810条经验 获得超5个赞

与其他答案相反,您必须深度克隆您的阵列:


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数组将通过引用进行复制,并且对其进行突变会改变原始数组的状态。


查看完整回答
反对 回复 2021-06-18
?
江户川乱折腾

TA贡献1851条经验 获得超5个赞

您可以使用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);

                });

            }

        });

    }


查看完整回答
反对 回复 2021-06-18
  • 3 回答
  • 0 关注
  • 144 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信