[英]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. .map
的目的是从旧数组生成一个新数组。 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.由于您没有返回任何内容,因此将生成
undefined
的数组。 This is probably a mistake, and therefore that lint rule is warning you about it.这可能是一个错误,因此该 lint 规则警告您。
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
在您的情况下,您似乎根本不关心 map 生成的数组,因此解决方法是使用更合适的方法,例如
.forEach
let categories = [];
items.forEach(cat => {
if (categories.indexOf(cat.category) === -1) {
categories.push(cat.category);
}
});
From the documentation on array-callback-return :从关于 array-callback-return的文档:
Array has several methods for filtering, mapping, and folding.
Array 有多种过滤、映射和折叠方法。 If we forget to write return statement in a callback of those, it's probably a mistake.
如果我们忘记在它们的回调中编写 return 语句,那可能是一个错误。 If you don't want to use a return or don't need the returned results, consider using .forEach instead.
如果您不想使用返回或不需要返回的结果,请考虑改用 .forEach。
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尝试使用迭代器 as for 或 forEach 映射不起作用从映射返回一个新数组想要渲染它可能是未定义的或在您的情况下,您似乎并不关心映射生成的数组所有,所以修复是使用更合适的方法,例如 .forEach 或 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.
如果您只想迭代项目并将一些值推送到类别数组,您可以使用 forEach 或 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.使用过滤器删除类别中已有类别的猫,并使用地图创建新的类别数组。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.