简体   繁体   English

使用地图时出现 ESlint 错误 - 解决方法?

[英]ESlint Error when using map - workaround?

What is the workaround to update the dataLine when using data.Items.map()使用data.Items.map()时更新dataLine的解决方法是什么

I am getting eslint error:我收到 eslint 错误:

Assignment to property of function parameter 'dataLine'

You can see I am deleting Other property and modifying dataLine.Config您可以看到我正在删除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));

About eslint, I think it's a missing piece, because if you write your function in an equivalent way:关于 eslint,我认为这是一个缺失的部分,因为如果您以等效的方式编写函数:

data.Items.map((dataLine) => {
  if (data.Type == "API") {
    dataLine.Config = {
      Size: "L"
    };
    delete dataLine.Other;
  }
  return dataLine;
});

you won't receive any warning.你不会收到任何警告。 Maybe it's the case of open an issue there.也许这是在那里打开问题的情况。

You could pass {props : true}, like GProst said, but this will enforce you to not make the assignment of any property of the parameter, which is a good thing, for example:您可以传递 {props : true} ,就像 GProst 所说的那样,但这将强制您不要分配参数的任何属性,这是一件好事,例如:

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;
});

Why eslint have such a rule?为什么 eslint 有这样的规则?

You are modifying the properties of data.Items, this will cause side effects on the external environment of the callback function on map.您正在修改 data.Items 的属性,这会对地图上的回调函数的外部环境产生副作用。 In some cases this will put you in bad situation, like not knowing which piece of code removed some property.在某些情况下,这会让你处于糟糕的境地,比如不知道哪一段代码删除了某些属性。

A suggestion about how you can deal with this safely is return an entire new object to make your data.Items immutable in your case:关于如何安全地处理这个问题的建议是返回一个全新的对象,使您的 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));

在 eslint 配置中编辑no-param-reassign规则,将 option props设置为false

"no-param-reassign": ["error", { "props": false }]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM