在ReactJ中加入依赖项数组时,使用效率不运行一次

发布于 2025-01-31 20:20:22 字数 862 浏览 2 评论 0 原文

我的问题是包括一个数组,即使使用使用效率也不会停止加载。其他问题不涵盖此主题;它们涵盖了相似但不同的方法。

我正在从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]);

My question is regarding including an array that doesn't stop loading even when using useEffect. Other questions do not cover this topic; they cover similar but different approaches.

I am fetching data from my firebasefirestore and setting the data required.

Now I only need the data to run once and to be displayed, but when i use the useEffect hook with the dependency (it doesn't work without the dependency), it starts running continuously and i can see in the network tab that it keeps on fetching the data non stop.

How can I fix this, what can i do to make my useEffect run only once even if it has a dependency array.

Here is my code:

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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

无力看清 2025-02-07 20:20:22

来自

将来,我们要添加一个功能,该功能允许React在保留状态时添加和删除UI部分。例如,当用户选项卡远离屏幕和背面时,React应该能够立即显示上一个屏幕。为此,反应将使用与以前相同的组件状态卸载并重新安装树。

此功能将为React应用程序提供更好的性能,但要求组件具有弹性,以使效果被多次安装和破坏。大多数效果将无需任何更改而起作用,但是有些效果认为它们仅安装或破坏一次。

正确的方法是跟踪它是否是第一个渲染,并将其用作执行代码效果的条件。这样,无论效果是否有零,一个或许多依赖关系都没关系。这是一个使用自定义钩子跟踪该状态的示例:

TS Playground

import {useEffect, useRef} from 'react';

function useIsFirstRender () {
  const ref = useRef(true);
  if (ref.current) {
    ref.current = false;
    return true;
  }
  return false;
}

function Component () {
  const isFirstRender = useIsFirstRender();

  useEffect(() => {
    // If it's not the first render, return early from the function
    if (!isFirstRender) return;
    // else, do other things...
    console.log('First render');
  });

  return null;
}

From the release notes for React v18:

In the future, we’d like to add a feature that allows React to add and remove sections of the UI while preserving state. For example, when a user tabs away from a screen and back, React should be able to immediately show the previous screen. To do this, React would unmount and remount trees using the same component state as before.

This feature will give React apps better performance out-of-the-box, but requires components to be resilient to effects being mounted and destroyed multiple times. Most effects will work without any changes, but some effects assume they are only mounted or destroyed once.

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

import {useEffect, useRef} from 'react';

function useIsFirstRender () {
  const ref = useRef(true);
  if (ref.current) {
    ref.current = false;
    return true;
  }
  return false;
}

function Component () {
  const isFirstRender = useIsFirstRender();

  useEffect(() => {
    // If it's not the first render, return early from the function
    if (!isFirstRender) return;
    // else, do other things...
    console.log('First render');
  });

  return null;
}

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文