我遇到了这样的挑战,我想要将数组的一部分加载到一个名为"loadedData"的新数组中,并且只显示loadedData,因为组件非常繁重.

然而,在第一次加载时,我在第一次加载时遇到了很多问题,因为useEffect似乎把它搞砸了.第一次加载将发生两次,并在每次渲染时将数组上的第一个数据推送一次.如果我删除了"reactStrictMode",它就会正常工作,但我不想在不了解其含义的情况下"作弊".有比我更了解的人把它放在那里是有原因的..

在初始加载期间,isLoding状态不会阻止第二次运行-这是我在其他与此问题相关的线程中倾向于得到的建议.

有人知道为什么第一个useEffect会忽略isLoding状态吗?该怎么办?

  // Try to load what is visible, but not more
  const [loadedData, setLoadedData] = useState([]);
  const [isLoading, setIsLoading] = useState(false);

const addMoreData = async () => {
    if (loadedData.length >= data.length) return;

    const startIndex = loadedData.length;
    const preferredLoadLength = 1;

    const endIndex = startIndex + preferredLoadLength;

    const newData = data.slice(startIndex, endIndex);

    setLoadedData((prev) => [...prev, ...newData]);
  };

  // Check on mount and after a fetch to see if the table is already scrolled to the bottom and immediately needs to fetch more data
  useEffect(() => {
    const { scrollHeight, scrollTop, clientHeight } = tableContainerRef.current;
    if (
      scrollHeight == clientHeight &&
      scrollTop == 0 &&
      loadedData.length < data.length
    ) {
      const addNewDataFunction = async () => {
        if (isLoading) {
          return;
        }
        setIsLoading(true);
        await addMoreData();
        setIsLoading(false);
      };
      addNewDataFunction();
    }
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [data.length, loadedData.length, isLoading]);

推荐答案

您只需在addMoreData函数中更改此行即可

setLoadedData((prev) => [...prev, ...newData]);

setLoadedData([...loadedData, ...newData]);

这将使状态在当前渲染期间基于其值进行更新,并且由于第二次运行useEffect时组件尚未重新渲染,因此第一个组件所做的更改仍未反映出来,因此loadedData尚未更新.

当您使用函数形式更新时,prev是状态的实时值,在使用严格模式进行开发时,您遇到的情况是预期的.

最后,go 掉isLoading个也无济于事.

Note:更推荐使用函数形式的setState,但在启用严格模式时不要在useEffect中使用,因为挂接在组件装载时运行两次.
此外,当您在依赖项数组中包括data.lengthloadedData.length时,每次更改其中一个值时都会触发useEffect.

Reactjs相关问答推荐

有没有方法覆盖NextJS 14中的布局?

如何防止使用useCallback和memo重新渲染

不同步渲染

useCallback()是否应该用于作为prop传递给子组件的函数,即使该组件包装在memo()中?

如何从Reaction-Arborist树获取排序数据

警告:遇到两个子元素拥有同一把 keys .键应该是唯一的,以便组件在更新时保持其身份

Redux 工具包不更新状态

在 React 中将 MUI 样式外包到单独的文件中?

如何在PrimeReact的表格中修改筛选图标功能

React设置上下文并进行导航

使用 MuiCssBaseline 在所有 MUI v5 标签上设置边距 0

损坏的图像 React useState

如何在 ReactJS 中提交后删除 URL 中的查询参数

如何在 React Native 中更新跨屏幕呈现的上下文状态变量?

需要在窗口调整大小时更新 React 组件

在 Spring Cloud Gateway 中运行的 React SPA 页面刷新出现白标错误

在 redux 中分派到另一个减少时状态值不会改变

为什么我在运行一些 npm react 命令时会收到这些警告?

点击提交后自动添加#

我想将悬停 colored颜色 更改为红色.写了一个话题,这个元素没有react ,怎么解决呢?