簡體   English   中英

如何修復 React 中的獲取和渲染問題?

[英]How to fix fetch and render issue in React?

我花了兩天時間試圖弄清楚發生了什么,但仍然無法弄清楚問題出在哪里。 太令人沮喪了:((

我在代碼沙箱上有此代碼,從 api 獲取月份和總計,然后進行簡單計算。

https://codesandbox.io/s/agitated-cdn-q3gju?file=/src/Card.js

第一個問題:每隔一次頁面刷新,屏幕上的值將首先呈現第一個總數,然后在第二次刷新時,它將呈現第二個總數。 (請參閱沙盒上的代碼以更好地理解我的意思)

第二個問題:當我嘗試 console.log revenue時,我在控制台上打印了兩次數組,不知道為什么它會獲取兩次。

第三個問題:我知道這可能與我的后端代碼(我在下面包含一個片段)有關,但我確實已經通過每一行調試並且無法發現錯誤。

非常感謝您的幫助

router.get("/incomestats", verifyTokenAndAdmin, async (req, res) => {
  const date = new Date();
  const lastMonth = new Date(date.setMonth(date.getMonth() - 1));
  const previousMonth = new Date(date.setMonth(lastMonth.getMonth() - 1));
  // const previousMonth =  new Date(new Date().setMonth(lastMonth.getMonth() - 1));
  try {
    const ordersData = await Order.aggregate([
      { $match: { createdAt: { $gte: previousMonth } } },
      { $project: { month: { $month: "$createdAt" }, sales: "$amount" } },
      { $group: { _id: "$month", total: { $sum: "$sales" } } },
    ]);
    res.status(200).json(ordersData);
  } catch (error) {
    res.status(500).json(error);
    console.log(error);
  }
});

主要問題在於您傳遞給useEffect調用的依賴數組。

useEffect(() => {
  const getRevenue = async () => {
    try {
      const res = ...;
      setRevenue(res.data);
      setDifference((res.data[1].total * 100) / (res.data[0].total - 100));
    } catch (error) {
      ...
    }
  };
  getRevenue();
}, [difference]);

當它應該是[setRevenue, setDifference]時,你有[difference] ] 。 通過包含difference ,您告訴反應它需要在差異發生變化時運行此效果但是您也在此處調用setDifference來更改difference的值。 這將無限循環。 將依賴項更改為[setRevenue, setDifference]將解決無限循環問題。

useEffect(() => {
  const getRevenue = async () => {
    try {
      const res = ...;
      setRevenue(res.data);
      setDifference((res.data[1].total * 100) / (res.data[0].total - 100));
    } catch (error) {
      ...
    }
  };
  getRevenue();
}, [setRevenue, setDifference]);

第二件事(有爭議甚至不是問題)是在useEffect內部,您在異步上下文中調用setRevenuesetDifference 在新 beta 版本 (18) 之前的 React 版本中,react 不會批處理這兩個 state 更新。 這個問題很好地解釋了imo。

暫無
暫無

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

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