3 回答

TA貢獻(xiàn)1810條經(jīng)驗(yàn) 獲得超5個(gè)贊
與其他答案相反,您必須深度克隆您的陣列:
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});
}
如果您不深度克隆您的數(shù)組,則該time_slots數(shù)組將通過引用進(jìn)行復(fù)制,并且對(duì)其進(jìn)行突變會(huì)改變?cè)紨?shù)組的狀態(tài)。

TA貢獻(xiàn)1851條經(jīng)驗(yàn) 獲得超5個(gè)贊
您可以使用Array.map函數(shù)作為,
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);
});
}
});
}
添加回答
舉報(bào)