简体   繁体   中英

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

How to fix error "no-param-reassign": [2, {"props": false}]"

This is example where I am getting the Eslint error:

 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. Either disable the linter rule for the line, or create new objects instead of mutating, eg:

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. This ensures that nothing is mutated.

Basically you're modifying your filterList in place with forEach , use map instead:


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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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