【问题标题】:How to solve "Expected to return a value in arrow function" error in eslint如何解决 eslint 中的“预期在箭头函数中返回值”错误
【发布时间】:2021-01-11 16:48:08
【问题描述】:

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

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

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

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

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

    setSelectedPrice(initialPrices);
  }, []);

【问题讨论】:

  • 不要使用map 来获得副作用。使用map 的输出或使用forEachfor 循环。

标签: javascript reactjs eslint


【解决方案1】:

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

【讨论】:

    【解决方案2】:

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

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

    【讨论】:

      【解决方案3】:

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

      【讨论】:

        【解决方案4】:

        从你的情况来看,你想填充initialPrices,然后传递setSelectedPricemap 方法不是解决方案,在这种情况下对您来说,因为此方法返回一个数组。 在您的情况下,一个安全的赌注是 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);
        

        reduce 示例:

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

        【讨论】:

          猜你喜欢
          • 2019-10-28
          • 2018-08-16
          • 1970-01-01
          • 1970-01-01
          • 2020-07-30
          • 2021-04-04
          • 1970-01-01
          • 1970-01-01
          • 2022-01-20
          相关资源
          最近更新 更多