【问题标题】:ESlint Error when using map - workaround?使用地图时出现 ESlint 错误 - 解决方法?
【发布时间】:2019-12-03 03:30:37
【问题描述】:
使用data.Items.map()时更新dataLine的解决方法是什么
我收到 eslint 错误:
Assignment to property of function parameter 'dataLine'
你可以看到我正在删除Other属性并修改dataLine.Config
const data = {
Type: "API",
Items: [{
State: [{Name: "Pending"}],
Config: {
Size: "M"
},
Other: "string.."
}]
}
const newItems = data.Items.map(({State,...dataLine}) => {
if (data.Type == "API") {
dataLine.Config = {
Size: "L"
};
delete dataLine.Other;
}
return dataLine;
});
console.log(JSON.stringify(newItems, null, 2));
【问题讨论】:
标签:
javascript
node.js
eslint
eslint-config-airbnb
【解决方案1】:
关于 eslint,我认为这是一个缺失的部分,因为如果你以等效的方式编写函数:
data.Items.map((dataLine) => {
if (data.Type == "API") {
dataLine.Config = {
Size: "L"
};
delete dataLine.Other;
}
return dataLine;
});
您不会收到任何警告。也许这是在那里打开问题的情况。
您可以像 GProst 所说的那样传递 {props : true},但这将强制您不要分配参数的任何属性,这是一件好事,例如:
const newItems = data.Items.map(({State,...dataLine}) => {
if (data.Type == "API") {
dataLine.Config = { // not allowed with props : true
Size: "L"
};
delete dataLine.Other; // not allowed with props : true
}
return dataLine;
});
为什么 eslint 有这样的规则?
您正在修改data.Items的属性,这将对地图回调函数的外部环境产生副作用。在某些情况下,这会使您陷入糟糕的境地,例如不知道哪段代码删除了某些属性。
关于如何安全处理此问题的建议是返回一个全新的对象以使您的 data.Items 在您的情况下不可变:
const data = {
Type: "API",
Items: [{
State: [{Name: "Pending"}],
Config: {
Size: "M"
},
Other: "string.."
}]
}
const newItems = data.Items.map(({State,...dataLine}) => {
const dataLineCopy = JSON.parse(JSON.stringify(dataLine))
if (data.Type == "API") {
dataLineCopy.Config = {
Size: "L"
};
delete dataLineCopy.Other;
}
return dataLineCopy;
});
console.log(JSON.stringify(newItems, null, 2));
【解决方案2】:
在 eslint 配置中编辑 no-param-reassign 规则,将选项 props 设置为 false:
"no-param-reassign": ["error", { "props": false }]