簡體   English   中英

如何解決 eslint 中的“預期在箭頭函數中返回值”錯誤

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

我正在使用 eslint 並收到此錯誤。

預計返回箭頭 function 中的值

錯誤顯示在代碼的第三行。

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

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

    setSelectedPrice(initialPrices);
  }, []);

map function 必須返回一個值。 如果要基於數組創建新的 object,則應改用reduce function。

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 function 應該返回一些東西。 情況並非如此,因此會發生錯誤。 也許減少 function 會比 map 更合適?

map function 旨在在您想在調用數組的每個元素上應用一些 function 時使用。 我認為這里最好使用forEach

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

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

    setSelectedPrice(initialPrices);
}, []);

從我在您的案例中可以看到,您想要填充initialPrices ,然后將其傳遞給setSelectedPrice map方法不是解決方案,在這種情況下對您來說,因為此方法返回一個數組。 在您的情況下,一個安全的賭注是for in loopforEachreduce function。

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM