我有一个处于状态的对象数组,如下所示:
this.state = {
week: [
{
en: 'Mon',
morn: false,
night: false,
},
//... the rest of the days...
我可以成功切换morn
和night
布尔值,就像这样:
this.setState(prevState => {
prevState.week.map(day => {
if (target.includes(day.en)) {
if (target.includes('morn')) {
day.morn = !day.morn;
//^ right here
}
if (target.includes('night')) {
day.night = !day.night;
//^ and here
}
}
return day;
});
});
eslint抱怨:Assignment to property of function parameter 'day'
。
答案 0 :(得分:1)
之所以会这样,是因为您的linter启用了以下规则: https://eslint.org/docs/rules/no-param-reassign
分配给声明为函数参数的变量可能会产生误导,并导致混乱的行为,因为修改函数参数也会使arguments对象发生变化。通常,对功能参数的分配是意料之外的,并且表明存在错误或程序员错误。
此规则也可以配置为在修改功能参数时失败。参数上的副作用会导致执行流程违反直觉,并使错误难以跟踪。
要解决此问题,您可以创建day
对象的副本,可以对其进行修改并返回该副本:
this.setState(prevState => {
prevState.week.map(day => {
const tempDay = {...day};
if (target.includes(day.en)) {
if (target.includes('morn')) {
tempDay.morn = !day.morn;
}
if (target.includes('night')) {
tempDay.night = !day.night;
}
}
return tempDay;
});
});