javascript - 如何解决函数中的 no-param-reassign 错误
问题描述
在 Node/JS 函数中,我得到 ESLintno-param-reassign
代码用于更新候选人如下
update(candidate) {
const { id } = candidate;
if (!id) {
throw new UserInputError('id is mandatory');
}
return this.tx(tableName)
.returning(Object.values(columnsByProperties))
.where('id', id)
.update(prepareCandidate(candidate))
.reduce((_, b) => camelcaseKeys(b), null)
.then(x => {
if (!x) {
throw new UserInputError(`Candidate "id" with ${id} is not found`);
}
x.preferredContact = x.preferredContactHours;
return x;
});
}
错误具体在这里Assignment to property of function parameter 'x'
.then(x => {
if (!x) {
throw new UserInputError(`Candidate "id" with ${id} is not found`);
}
x.preferredContact = x.preferredContactHours;
return x;
});
解决方案
您可以更换:
x.preferredContact = x.preferredContactHours;
return x;
有了这个:
return { ...x, preferredContact: x.preferredContactHours };
这样您就可以返回一个新对象,而不是修改函数的参数。
现在,详细说明一下。正如规则的文档所说:
对声明为函数参数的变量赋值可能会产生误导并导致混淆行为,因为修改函数参数也会改变 arguments 对象。
“令人困惑的行为”应理解为例如奇怪的副作用。我记得在一个应用程序中造成了严重破坏,因为在一个函数内部,我改变了一个作为参数传递的数组。调用代码中的数组也发生了变异,这是bad。这就是 ESLint 有助于防止的事情!
推荐阅读
- javascript - 当我调用 google-plus 的登录功能时出现错误
- java - 带有变量名的命令行参数
- c - 将 3D 数组的 memcpy 列转换为 1D 数组
- mysql - 从字符串中删除连续的重复字符
- c# - 水晶报表加载失败问题
- java - 自动将 JTextFilds 放在 GUI 上,repaint()
- php - PHP:从 PHP 生成 HTML 文件
- python - Python:如何从 shapefile 计算指标的空间自相关?
- android - Android VideoView:视频播放,但抛出 java.io.FileNotFoundException
- r - Windows10 中 R 的 Ubuntu 终端