简体   繁体   中英

How to fix "Expected to return a value in arrow function array-callback-return"?

I don't understand, are you required to return a specific way through map?

componentDidMount() {
  // read the items db
  let categories = [];
  items.map(cat => {
    if (categories.indexOf(cat.category) === -1) {
      categories.push(cat.category);
    }
  });
  console.log(categories);
  this.setState({ categories: categories });
}

The purpose of .map is to produce a new array from an old one. The return value from your function specifies what the new value at that spot in the array should be. Since you're not returning anything an array of undefined 's will be produced. This is probably a mistake, and therefore that lint rule is warning you about it.

In your case, you don't seem to care about the array that map produces at all, so the fix is to use a more appropriate method, such as .forEach

let categories = [];
items.forEach(cat => {
  if (categories.indexOf(cat.category) === -1) {
    categories.push(cat.category);
  }
});

From the documentation on array-callback-return :

Array has several methods for filtering, mapping, and folding. If we forget to write return statement in a callback of those, it's probably a mistake. If you don't want to use a return or don't need the returned results, consider using .forEach instead.

try to use iterator as for or forEach map don't work the purpose from the map it returns a new array from want to render it may be undefined or In your case, you don't seem to care about the array that map produces at all, so the fix is to use a more appropriate method, such as .forEach or for

 let categories = []; const items = []; for (let cat in items) { if (categories.indexOf(cat.category) === -1) { categories.push(cat.category); } }; console.log(categories);

enter code here

Yes, it requires you to return something to create the new array. If you just want to iterate items and push some values to categories array, you can use forEach or for...of.

 this.setState({ categories: items.filter(cat => categories.indexOf(cat.category) === -1).map(cat => cat.category) })

Use filter to remove cat with category already in categories, and use map to create a new categories array.

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