如何解决eslint中的"Expected to return a value in arrow function"错误

How to solve "Expected to return a value in arrow function" error in eslint

我正在使用 eslint 并收到此错误。

Expected to return a value in arrow function

错误显示在代码的第三行。

  useEffect(() => {
    let initialPrices = {};

    data.map(({ category, options }) => {
      initialPrices = {
        ...initialPrices,
        [category]: options[0].price,
      };
    });

    setSelectedPrice(initialPrices);
  }, []);

您的 map 函数应该 return 一些东西。这里不是这种情况,所以错误发生了。也许 reduce 函数比 map 更合适?

map 函数必须 return 一个值。如果你想创建一个基于数组的新对象,你应该使用 reduce 函数。

const reducer = (accumulator, { category, options }) => (
{...accumulator, [category]:options[0].price}
)
const modifiedData = data.reduce(reducer)

更多信息https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/reduce

当您想对调用数组的每个元素应用某些函数时,可以使用 map 函数。我认为这里最好使用 forEach:

useEffect(() => {
    let initialPrices = {};

    data.forEach(({ category, options }) => {
      initialPrices = {
        ...initialPrices,
        [category]: options[0].price,
      };
    });

    setSelectedPrice(initialPrices);
}, []);

根据我在您的案例中看到的情况,您想要填充 initialPrices,然后再传递它 setSelectedPrice。在这种情况下,map 方法不是解决方案,因为此方法 returns 是一个数组。 在您的情况下,一个安全的选择是 for in loopforEachreduce 函数。

const data = [
  {

    category: "ball",
    options: [
      {
        price: "120.45"
      }
    ]
  },
  {

    category: "t-shirt",
    options: [
      {
        price: "12.45"
      }
    ]
  }
];

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);

减少示例:

const initialPrices = Object.values(data).reduce((accumulatorObj, { category, options}) => {
        accumulatorObj[category] = options[0].price
  return accumulatorObj;
}, {});
setSelectedPrice(initialPrices);