[英]How to solve "Expected to return a value in arrow function" error in eslint
I am using eslint and getting this error.我正在使用 eslint 并收到此错误。
Expected to return a value in arrow function
预计返回箭头 function 中的值
The error is showing on the third line of the code.错误显示在代码的第三行。
useEffect(() => {
let initialPrices = {};
data.map(({ category, options }) => {
initialPrices = {
...initialPrices,
[category]: options[0].price,
};
});
setSelectedPrice(initialPrices);
}, []);
The map
function must return a value. map
function 必须返回一个值。 If you want to create a new object based on an array you should use the reduce
function instead.如果要基于数组创建新的 object,则应改用
reduce
function。
const reducer = (accumulator, { category, options }) => (
{...accumulator, [category]:options[0].price}
)
const modifiedData = data.reduce(reducer)
More information https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/reduce更多信息https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/reduce
Your map
function should return something.您的
map
function 应该返回一些东西。 Here it's not the case so the error happens.情况并非如此,因此会发生错误。 Maybe a reduce function will be more appropriate than map?
也许减少 function 会比 map 更合适?
The map
function is intended to be used when you want to apply some function over every element of the calling array. map
function 旨在在您想在调用数组的每个元素上应用一些 function 时使用。 I think here it's better to use a forEach
:我认为这里最好使用
forEach
:
useEffect(() => {
let initialPrices = {};
data.forEach(({ category, options }) => {
initialPrices = {
...initialPrices,
[category]: options[0].price,
};
});
setSelectedPrice(initialPrices);
}, []);
From what I can see in your case, is that you want to populate initialPrices
, and after that to pass it setSelectedPrice
.从我在您的案例中可以看到,您想要填充
initialPrices
,然后将其传递给setSelectedPrice
。 The map
method is not a solution, for you in this case, because this method returns an array. map
方法不是解决方案,在这种情况下对您来说,因为此方法返回一个数组。 A safe bet in your case would a for in loop
, a forEach
, or a reduce
function.在您的情况下,一个安全的赌注是
for in loop
、 forEach
或reduce
function。
const data = [
{
category: "ball",
options: [
{
price: "120.45"
}
]
},
{
category: "t-shirt",
options: [
{
price: "12.45"
}
]
}
];
The forEach example: forEach 示例:
let initialPrices = {};
// category and options are destructured from the first parameter of the method
data.forEach(({ category, options}) => {
initialPrices[category] = options[0].price;
});
// in this process I'm using the Clojure concept to add dynamically the properties
setSelectedPrice(initialPrices);
The reduce example:减少示例:
const initialPrices = Object.values(data).reduce((accumulatorObj, { category, options}) => {
accumulatorObj[category] = options[0].price
return accumulatorObj;
}, {});
setSelectedPrice(initialPrices);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.