我有下面的代码,我试图用对象数组中修改的几个属性来更新setState
onClick(index) {
let tmp = this.state.daysOfWeek;
tmp[index].active = !tmp[index].active;
if (tmp[index].active === true) {
tmp[index].className = "selectedDay";
} else {
tmp[index].className = "remSelectedDay";
}
this.setState({ daysOfWeek: [...this.state.daysOfWeek, tmp]})
}
这里tmp是对象的修改数组。如果我使用传播运算符,则对象的携带将与tmp合并。
如何使用对象数组更新当前状态?
答案 0 :(得分:1)
结合使用map
和功能形式setState
,可以在不直接修改状态的情况下正确更新数组:
onClick(index){
this.setState(state => {
return {
daysOfWeek: state.daysOfWeek.map((day, i) => {
if (i === index) {
return {
...day,
active: !day.active,
className: day.active ? 'remSelectedDay' : 'selectedDay'
}
}
return day;
})
}
})
}
答案 1 :(得分:0)
onClick (index) {
const { daysOfWeek } = this.state // for example: [1, 2, 3, 4, 5], index = 1
this.setState({
daysOfWeek: [
...daysOfWeek.slice(0, index), // [1]
{
...daysOfWeek[index], // this is 2
active: !daysOfWeek[index],
className: daysOfWeek[index] ? 'selectedDay' : 'remSelectedDay'
},
...daysOfWeek.slice(index + 1) // [3, 4, 5]
]
})
}