简体   繁体   English

如何修复 React 中的获取和渲染问题?

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

I have spent two days trying to figure out what's going on and still can't figure out where the issue is.我花了两天时间试图弄清楚发生了什么,但仍然无法弄清楚问题出在哪里。 It's so frustrating:((太令人沮丧了:((

I have this code on code sandbox fetching from an api the month and total then doing simple calculations.我在代码沙箱上有此代码,从 api 获取月份和总计,然后进行简单计算。

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

The first issue: With every other page refresh, the value on screen will first render the first total then on the second refresh, it will render the second total.第一个问题:每隔一次页面刷新,屏幕上的值将首先呈现第一个总数,然后在第二次刷新时,它将呈现第二个总数。 (please see the code on sandbox to understand better what I mean) (请参阅沙盒上的代码以更好地理解我的意思)

The second issue: when I try to console.log the revenue I get the array printed on the console twice, not sure why it's fetching it twice.第二个问题:当我尝试 console.log revenue时,我在控制台上打印了两次数组,不知道为什么它会获取两次。

The third issue: I understand that it might be something to do with my backend code (which I'm including a snippet below) but I really have gone through each line to debug and can't spot the mistake.第三个问题:我知道这可能与我的后端代码(我在下面包含一个片段)有关,但我确实已经通过每一行调试并且无法发现错误。

Your help is so much appreciated非常感谢您的帮助

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

The primary issues is with the dependency array that you passed into your useEffect call.主要问题在于您传递给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]);

You have [difference] when it should be [setRevenue, setDifference] .当它应该是[setRevenue, setDifference]时,你有[difference] ] 。 By including difference you are telling react that it needs to run this effect when difference changes HOWEVER you are also calling setDifference here which changes the value of difference .通过包含difference ,您告诉反应它需要在差异发生变化时运行此效果但是您也在此处调用setDifference来更改difference的值。 This will infinitely loop.这将无限循环。 Changing the dependencies to [setRevenue, setDifference] will resolve the infinite loop problem.将依赖项更改为[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]);

The second thing (which debatably isn't even an issue) is that inside useEffect you are calling setRevenue and setDifference in an asynchronous context.第二件事(有争议甚至不是问题)是在useEffect内部,您在异步上下文中调用setRevenuesetDifference In versions of React before the new beta version (18) react doesn't batch these two state updates.在新 beta 版本 (18) 之前的 React 版本中,react 不会批处理这两个 state 更新。 This question explains it really well imo. 这个问题很好地解释了imo。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM