如何解决eslint中“预期返回箭头函数中的值”错误

时间:2021-01-11 16:48:08

标签: javascript reactjs eslint

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

<块引用>

期望在箭头函数中返回一个值

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

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

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

    setSelectedPrice(initialPrices);
  }, []);

3 个答案:

答案 0 :(得分:2)

map 函数必须返回一个值。如果要基于数组创建新对象,则应改用 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

答案 1 :(得分:1)

您的 map 函数应该返回一些东西。情况并非如此,因此会发生错误。也许 reduce 函数比 map 更合适?

答案 2 :(得分:1)

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

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

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

    setSelectedPrice(initialPrices);
}, []);