javascript - 箭头函数不应返回赋值 Eslint

标签 javascript reactjs eslint eslint-config-airbnb

我正在映射从 API 返回的值,并在值不存在时添加一个虚拟值作为防御代码。为此,我使用 JS Map 来获取结果。但不幸的是我收到 eslint 错误 Arrow function should not return assignment 。在这里我分享我实现的代码。请检查并建议我最好的解决方案。我不想禁用 eslint 错误。提前致谢。

代码:

 const chartData = res.data.map(
    (data) => data.latestMetric = data.latestMetric === null ? dummyLatestMetric : data.latestMetric
  );

错误:

箭头函数不应返回赋值。 eslint(无返回分配)

最佳答案

<强> Arrow Function

An arrow function expression is a syntactically compact alternative to a regular function expression, although without its own bindings to the this, arguments, super, or new.target keywords. Arrow function expressions are ill suited as methods, and they cannot be used as constructors.

<强> Map Function

The map() method creates a new array populated with the results of calling a provided function on every element in the calling array.

<小时/>

.map() 函数需要您为每次迭代返回一个值。如果您只想循环遍历数组来产生副作用,可以考虑 forEach 或其他循环函数。

就您而言,我看到您想有条件地修改 res.data 中的 latestMetric,您可以执行以下操作:

const chartData = res.data.map(data => ({
  ...data,
  latestMetric: data.latestMetric === null ? dummyLatestMetric : data.latestMetric,
});

spread syntax会将 data 属性分散到一个新对象中,然后我们根据条件有条件地设置 latestMetric 的值

如果你不想使用展开语法,也可以使用传统的 Object.assign方法:

const chartData = res.data.map(data => Object.assign({}, data, {
  latestMetric: data.latestMetric === null ? dummyLatestMetric : data.latestMetric,
});
<小时/>

关于您的防御策略,您可能有兴趣使用 || 语法,但要小心,因为它验证所有虚假值(它包括:false0null未定义等)

const chartData = res.data.map(data => ({
  ...data,
  latestMetric: data.latestMetric || dummyLatestMetric,
});
<小时/>

最后但并非最不重要的一点是,您最好先了解 ESLint 规则,并阅读该编码实践背后的原因,看看您是否想使用该规则,或修改它,甚至在您的项目中禁用它.

引用号:https://eslint.org/docs/rules/no-return-assign

关于javascript - 箭头函数不应返回赋值 Eslint,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61262422/

相关文章:

javascript - 从 shell 将变量参数传递给 Spidermonkey javascript

reactjs - React 中的 Antd 表

javascript - 在没有引荐来源网址的情况下,Google、Facebook 等如何找出您来自哪个网站?

javascript - 在html页面中显示用户地理位置

javascript - 如何在useEffect中使用更新的值

reactjs - react : Passing the parent into a child

reactjs - 如何动态改变jsx中的react元素

angular - 有 Angular 迁移 TSLint 到 ESLint Banana-In-Box 错误

node.js - 在 reactjs 中使用 npm uuid

javascript - 变量已定义并用作方法参数,但从未使用过值,因此获取 ESLint 未使用的变量