简体   繁体   English

如何解决“无参数重新分配”的错误?

[英]How to fix “no-param-reassign” eslint error?

How to fix error "no-param-reassign": [2, {"props": false}]" 如何解决错误"no-param-reassign": [2, {"props": false}]"

This is example where I am getting the Eslint error: 这是我收到Eslint错误的示例:

 filtersList.forEach((filter) => {
      if (filter.title === 'Timeframe') {
        filter.options.forEach((obj) => {
          obj.selected = false;
        });
      }
    });

How to fix this? 如何解决这个问题?

Your existing code mutates objects in the parameter array, which is causing the linter error. 您现有的代码会使参数数组中的对象发生变异,这会导致linter错误。 Either disable the linter rule for the line, or create new objects instead of mutating, eg: 禁用该行的linter规则,或者创建新对象而不是进行更改,例如:

const changedFilters = filtersList.map((filter) => {
  if (filter.title !== 'Timeframe') {
    // you can clone the object here too, if you want
    return filter;
  }
  return {
    ...filter,
    options: filter.options.map((obj) => ({
      ...obj,
      selected: false
    }))
  };
});

Then use the changedFilters variable later on in the code. 然后,稍后在代码中使用changedFilters变量。 This ensures that nothing is mutated. 这样可以确保没有任何变异。

Basically you're modifying your filterList in place with forEach , use map instead: 基本上,您是使用forEach在适当位置修改filterList ,请改用map


filtersList.map(filter => {
  if (filter.title === "Timeframe") {
    return {
      ...filter,
      options: filter.options.map(obj => ({ ...obj, selected: false }))
    };
  }
  return filter;
});

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

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