在ReactJ中加入依赖项数组时,使用效率不运行一次
我的问题是包括一个数组,即使使用使用效率也不会停止加载。其他问题不涵盖此主题;它们涵盖了相似但不同的方法。
我正在从FirebaseFirestore获取数据并设置所需的数据。
现在,我只需要运行一次并且要显示的数据,但是当我将使用效果挂钩与依赖关系使用时(没有依赖关系,它不起作用),它开始连续运行,我可以在网络选项卡中看到它保留在不停止数据时获取数据。
我该如何修复此问题,即使它具有依赖关系数组,我该怎么做才能使我的使用效应仅运行一次。
这是我的代码:
import React, { Component, useEffect, useState, useCallback } from "react";
const [agentData, setAgentData] = useState([]);
const [agentID, setAgentID] = useState("");
const getSalesAgentInformation = async () => {
await firebase
.firestore()
.collection("Employees")
.where("employeeID", "==", agentID)
.get()
.then((snapshot) => {
const salesAgent = snapshot.docs.map((doc) => doc.data());
setAgentData(salesAgent);
});
};
useEffect(() => {
getSalesAgentInformation();
}, [agentData]);
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
来自:
正确的方法是跟踪它是否是第一个渲染,并将其用作执行代码效果的条件。这样,无论效果是否有零,一个或许多依赖关系都没关系。这是一个使用自定义钩子跟踪该状态的示例:
TS Playground
From the release notes for React v18:
The right way to do this is to keep track of whether or not it’s the first render and use that as a condition for executing your code in the effect. This way, it doesn't matter whether there are zero, one, or many dependencies for the effect. Here's an example which uses a custom hook to track that state:
TS Playground