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

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);
});
}
});
}
添加回答
举报