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);
});
}
});
}
添加回答
舉報
