AskOverflow.Dev

AskOverflow.Dev Logo AskOverflow.Dev Logo

AskOverflow.Dev Navigation

  • 主页
  • 系统&网络
  • Ubuntu
  • Unix
  • DBA
  • Computer
  • Coding
  • LangChain

Mobile menu

Close
  • 主页
  • 系统&网络
    • 最新
    • 热门
    • 标签
  • Ubuntu
    • 最新
    • 热门
    • 标签
  • Unix
    • 最新
    • 标签
  • DBA
    • 最新
    • 标签
  • Computer
    • 最新
    • 标签
  • Coding
    • 最新
    • 标签
主页 / coding / 问题 / 79019560
Accepted
Sharon
Sharon
Asked: 2024-09-25 00:33:03 +0800 CST2024-09-25 00:33:03 +0800 CST 2024-09-25 00:33:03 +0800 CST

在 React Native 中实现无限滚动

  • 772

我在网上看到了一些解决方案,但我无法让它们发挥作用。

我有一个 React Native 应用,它从 API 加载数据。数据是分页的;每次我检索一个页面时,我都会收到该页面的结果以及下一页的 URL。因此,API 的典型响应采用以下格式(显然它比这更复杂一些,但这是要点):

{
  data: [
    { key: xx, title: 'Item 1' },
    { key: yy, title: 'Item 2' }
  ], 
  next: 'www/url/to/next/page/of/results'
}

我想在屏幕上显示每个项目,并且当用户滚动到屏幕底部时,应该加载下一组结果。我正在尝试FlatList为此使用。

到目前为止我已经(我还没有进行任何类型的错误检查或任何操作;只是试图先让它工作):

const HomeScreen = () => {
  const [next, setNext] = React.useState<string>(BASE_URL); // URL of first page of results
  const [isLoading, setIsLoading] = React.useState<boolean>(true);
  const [displayItems, setDisplayItems] = React.useState<Item[]|null>(null);

  // Get next page of items
  const fetchItems = async () => {
    setIsLoading(true);
    const response = await client(next, 'GET'); // Just calls axios
    setDisplayItems((items) => items.concat(response.data));
    setNext(response.next);
    setIsLoading(false);
  };

  // Get items on first loading screen
  React.useEffect(() => {
    fetchItems();
  }, [fetchItems]);

  // Show items
  if (isLoading) return <LoadingSpinner />
  if (displayItems && displayItems.length === 0) return <Text>Nothing to show</Text>
  return <FlatList
        onEndReachedThreshold={0}
        onEndReached={fetchItems}
        data={displayItems}
        renderItem={(i) => <ShowItem item={i}/>} />
    
};

export default HomeScreen;

问题在于它会标记一个错误,指出The 'fetchItems' function makes the dependencies of useEffect Hook change on every render.。它建议To fix this, wrap the definition of 'fetchItems' in its own useCallback() Hook.。

所以我把它包在一个useCallback()钩子里:

  const fetchItems = React.useCallback(async () => {
    setIsLoading(true);
    const response = await client(next, 'GET'); // Just calls axios
    setDisplayItems((items) => items.concat(response.data));
    setNext(response.next);
    setIsLoading(false);
  }, [next]);

除非我添加,否则它根本无法运行fetchItems(),但此时它会无限地重新渲染。

我在网上找不到任何可行的方法。令人恼火的是,我记得几年前为另一个项目实施过这个,但我不记得它特别复杂!任何帮助都感激不尽。

react-native
  • 2 2 个回答
  • 22 Views

2 个回答

  • Voted
  1. PhantomSpooks
    2024-09-25T01:23:35+08:002024-09-25T01:23:35+08:00

    您对 useEffect 的评论表明该效果的目的是在初始渲染时获取数据;因此您需要向该效果添加条件以确保它能够做到这一点:

    // Get items on first loading screen
      React.useEffect(() => {
        if(displayItems == null) fetchItems();
      }, [fetchItems,displayItems]);
    

    这样做时,当fetchItems或displayItems发生变化时会调用 useEffect,但只有fetchItems当为displayItemsnull(其初始状态)时才会调用。我认为没有必要用 useCallback 包装,但无论是否包装,fetchItems此效果都应该有效。fetchItems

    • 1
  2. Best Answer
    Ahmad Quraishi
    2024-09-25T03:06:34+08:002024-09-25T03:06:34+08:00

    对于您在问题中提到的主要错误:

    1. 如果没有React.useCallback,则每次渲染(或状态更新)时,例如,都会创建setNext(response.next)一个新的 引用。这会强制再次触发 ,从而导致再次调用。这会产生无限的 API 调用和重新渲染循环。fetchItemsuseEffectfetchItems
    2. 使用React.useCallback,由于您已next在依赖项数组中包含(状态变量),并且在函数next内进行更新fetchItems,因此当next更新时,React.useCallback将返回对 的新引用fetchItems,从而useEffect将再次被触发。

    简单的解决方案:从依赖数组fetchItems中删除useEffect,以避免不必要地触发重新渲染。

    最佳实践:

    • 使用useRef而不是useStatefor next:这可以防止不必要的重新渲染,因为 useRef 更新时不会触发重新渲染,这与 useState 不同。
    • onEndReached仅当没有正在进行的 API 调用(数据提取)时才应调用:实现标志(isLoading)或条件以确保在已经发生提取时不会触发其他提取。
    • 用途keyExtractor:始终确保每个列表项都有一个稳定且唯一的键,以帮助 React 高效优化渲染。

    以下是示例解决方案:

    import React, {useRef} from 'react';
    import {FlatList} from 'react-native';
    
    const HomeScreen = () => {
      const [isLoading, setIsLoading] = useState<boolean>(true);
      const [displayItems, setDisplayItems] = useState<Item[] | null>(null);
    
      const nextRef = useRef(BASE_URL);
    
      const fetchItems = async () => {
        setIsLoading(true);
        const response = await client(nextRef.current, 'GET'); // Just calls axios
        setDisplayItems((items) => items.concat(response.data));
        nextRef.current = response.next;
        setIsLoading(false);
      };
    
      React.useEffect(() => {
        fetchItems();
      }, []);
    
      const onEndReached = () => {
        if (!isLoading) {
          fetchItems()
        }
      }
    
      const listEmptyComponent = () => {
        if (!isLoading && displayItems?.length === 0) {
          return (
            <Text>Nothing to show</Text>
          )
        }
      }
    
      const renderItem = ({item}) => {
        return <ShowItem item={item}/>
      }
    
      const listFooterComponent = () => {
        if (isLoading && displayItems?.length > 0) {
          return <LoadingSpinner/>
        }
      }
    
      return (
        <FlatList
          data={displayItems}
          onEndReached={onEndReached}
          renderItem={renderItem}
          ListFooterComponent={listFooterComponent}
          ListEmptyComponent={listEmptyComponent}
          keyExtractor={(item) => item.id}
        />
      )
    
    };
    
    export default HomeScreen;

    • 1

相关问题

  • 从同级组件访问 DrawerStatus

  • 反应本机按钮不响应样式表更改(居中按钮)

  • 反应原生元素输入边框底部问题,​​带半径

  • 仅当拉动发生在 FlatList 组件周围时,拉动刷新才有效

  • 电子邮件未发送到 *.js 中的用户电子邮件地址

Sidebar

Stats

  • 问题 205573
  • 回答 270741
  • 最佳答案 135370
  • 用户 68524
  • 热门
  • 回答
  • Marko Smith

    Vue 3:创建时出错“预期标识符但发现‘导入’”[重复]

    • 1 个回答
  • Marko Smith

    为什么这个简单而小的 Java 代码在所有 Graal JVM 上的运行速度都快 30 倍,但在任何 Oracle JVM 上却不行?

    • 1 个回答
  • Marko Smith

    具有指定基础类型但没有枚举器的“枚举类”的用途是什么?

    • 1 个回答
  • Marko Smith

    如何修复未手动导入的模块的 MODULE_NOT_FOUND 错误?

    • 6 个回答
  • Marko Smith

    `(表达式,左值) = 右值` 在 C 或 C++ 中是有效的赋值吗?为什么有些编译器会接受/拒绝它?

    • 3 个回答
  • Marko Smith

    何时应使用 std::inplace_vector 而不是 std::vector?

    • 3 个回答
  • Marko Smith

    在 C++ 中,一个不执行任何操作的空程序需要 204KB 的堆,但在 C 中则不需要

    • 1 个回答
  • Marko Smith

    PowerBI 目前与 BigQuery 不兼容:Simba 驱动程序与 Windows 更新有关

    • 2 个回答
  • Marko Smith

    AdMob:MobileAds.initialize() - 对于某些设备,“java.lang.Integer 无法转换为 java.lang.String”

    • 1 个回答
  • Marko Smith

    我正在尝试仅使用海龟随机和数学模块来制作吃豆人游戏

    • 1 个回答
  • Martin Hope
    Aleksandr Dubinsky 为什么 InetAddress 上的 switch 模式匹配会失败,并出现“未涵盖所有可能的输入值”? 2024-12-23 06:56:21 +0800 CST
  • Martin Hope
    Phillip Borge 为什么这个简单而小的 Java 代码在所有 Graal JVM 上的运行速度都快 30 倍,但在任何 Oracle JVM 上却不行? 2024-12-12 20:46:46 +0800 CST
  • Martin Hope
    Oodini 具有指定基础类型但没有枚举器的“枚举类”的用途是什么? 2024-12-12 06:27:11 +0800 CST
  • Martin Hope
    sleeptightAnsiC `(表达式,左值) = 右值` 在 C 或 C++ 中是有效的赋值吗?为什么有些编译器会接受/拒绝它? 2024-11-09 07:18:53 +0800 CST
  • Martin Hope
    The Mad Gamer 何时应使用 std::inplace_vector 而不是 std::vector? 2024-10-29 23:01:00 +0800 CST
  • Martin Hope
    Chad Feller 在 5.2 版中,bash 条件语句中的 [[ .. ]] 中的分号现在是可选的吗? 2024-10-21 05:50:33 +0800 CST
  • Martin Hope
    Wrench 为什么双破折号 (--) 会导致此 MariaDB 子句评估为 true? 2024-05-05 13:37:20 +0800 CST
  • Martin Hope
    Waket Zheng 为什么 `dict(id=1, **{'id': 2})` 有时会引发 `KeyError: 'id'` 而不是 TypeError? 2024-05-04 14:19:19 +0800 CST
  • Martin Hope
    user924 AdMob:MobileAds.initialize() - 对于某些设备,“java.lang.Integer 无法转换为 java.lang.String” 2024-03-20 03:12:31 +0800 CST
  • Martin Hope
    MarkB 为什么 GCC 生成有条件执行 SIMD 实现的代码? 2024-02-17 06:17:14 +0800 CST

热门标签

python javascript c++ c# java typescript sql reactjs html

Explore

  • 主页
  • 问题
    • 最新
    • 热门
  • 标签
  • 帮助

Footer

AskOverflow.Dev

关于我们

  • 关于我们
  • 联系我们

Legal Stuff

  • Privacy Policy

Language

  • Pt
  • Server
  • Unix

© 2023 AskOverflow.DEV All Rights Reserve