【问题标题】:How to fix fetch and render issue in React?如何修复 React 中的获取和渲染问题?
【发布时间】:2022-01-20 02:12:44
【问题描述】:

我花了两天时间试图弄清楚发生了什么,但仍然无法弄清楚问题出在哪里。好郁闷:((

我在代码沙箱上有这段代码,它从 api 获取月份和总计,然后进行简单的计算。

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

第一个问题:每隔一次页面刷新,屏幕上的值将首先呈现第一个总数,然后在第二次刷新时,它将呈现第二个总数。 (请查看沙盒上的代码以更好地理解我的意思)

第二个问题:当我尝试 console.log revenue 时,我在控制台上打印了两次数组,不知道为什么它会获取两次。

第三个问题:我知道这可能与我的后端代码有关(我在下面包含了一个 sn-p)但我确实已经通过每一行来调试和无法发现错误。

非常感谢您的帮助????

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

【问题讨论】:

    标签: javascript reactjs


    【解决方案1】:

    主要问题在于您传递给 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]);
    

    你有[difference],而它应该是[setRevenue, setDifference]。通过包含difference,您告诉react 它需要在差异发生变化时运行此效果但是您还在这里调用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 不会batch 这两个状态更新。 This question 解释得很好 imo。

    【讨论】:

    • @davidio,您确实想安装npmjs.com/package/eslint-plugin-react-hooks,如果您的useEffect 挂钩中缺少依赖项或有多余的依赖项,它会警告您
    • 非常感谢。我试过这样做,但不幸的是它并没有解决问题,当我尝试手动添加数据时(参见 data.js 文件)它工作得很好,所以我不认为这是 useEffect 的问题。
    猜你喜欢
    • 2019-04-28
    • 1970-01-01
    • 1970-01-01
    • 2023-03-04
    • 2021-08-16
    • 2021-10-31
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多