[英]Array.prototype.map() expects a value to be returned at the end of arrow function
I have this array.map() arrow function and have the following error: "Array.prototype.map() expects a value to be returned at the end of arrow function array-callback-return"我有这个 array.map() 箭头函数并有以下错误:“Array.prototype.map() 期望在箭头函数数组回调返回的末尾返回一个值”
Here is my code:这是我的代码:
{productList.map((val) => {
const category = val.CategoryName;
// const quantity = val.ProductQuantity
if (category === "MotorcycleParts") {
if (val.ProductQuantity !== 0) {
return (
<div>
<div>
<div class="buyNowBtnDiv">
{localStorage.getItem("username") === "" ||
localStorage.length === 0 ? (
<div id="buyAddBtn">
</div>
) : (
<div id="buyAddBtn">
</div>
)}
</div>
</div>
</div>
);
}
}
})}
I have read about the error and I see it has something to do with requiring a returning value, but I do have this?我已经阅读了有关该错误的信息,我发现它与需要返回值有关,但我确实有这个错误?
A code example with a fix would help, I think it would be something simple.带有修复的代码示例会有所帮助,我认为这很简单。
map
has to return a value for each item. map
必须为每个项目返回一个值。
If you want to do some filtering, you should consider using Array.prototype.filter()
before, so you can remove the if
s in your map.如果你想做一些过滤,你应该考虑使用
Array.prototype.filter()
之前,这样你就可以删除地图中的if
。
The code is also way more easy to read.代码也更容易阅读。
{productList.filter(val => val.CategoryName === "MotorcycleParts" && val.ProductQuantity !== 0)
.map((val) => {
return (
<div>
<div>
<div class="buyNowBtnDiv">
{localStorage.getItem("username") === "" ||
localStorage.length === 0 ? (
<div id="buyAddBtn">
</div>
) : (
<div id="buyAddBtn">
</div>
)}
</div>
</div>
</div>
);
})}
You could just return null when the listed conditions are not matched:当列出的条件不匹配时,您可以只返回 null:
{productList.map((val) => {
const category = val.CategoryName;
// const quantity = val.ProductQuantity
if (category === "MotorcycleParts") {
if (val.ProductQuantity !== 0) {
return (
<div>
<div>
<div class="buyNowBtnDiv">
{localStorage.getItem("username") === "" ||
localStorage.length === 0 ? (
<div id="buyAddBtn">
</div>
) : (
<div id="buyAddBtn">
</div>
)}
</div>
</div>
</div>
);
}
return null;
}
})}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.