使用 ScrollView 的 InfiniteScroll - React Native

Tha*_*rio 2 pagination lazy-loading scrollview reactjs react-native

我有一个使用 React Native 本身的 ScrollView 的列表。基本上,我通过 API 返回动态构建一个列表。

\n
async fetchData(userSearch) {\n    const {route} = this.props;\n    const {params} = route;\n    const {type} = params;\n\n    this.setState({\n      loading: true,\n    });\n\n    const responseProcedures = await scheduleResource.getProcedures(userSearch);\n\n    this.setState({\n      procedures: responseProcedures.data,\n      loading: false,\n    });\n  }\n\n\n\n<ScrollView\n  onScroll={(event) => this.shouldLoadMoreContent(event)}\n>\n    {procedures.map(procedure => (\n      <ArrowBox key={procedure.id} onPress={() => RootNavigation.navigate('ProcedureDetails', {procedure})}>\n        <Text bold style={styles.ProcedureTitle}>\n          {procedure.name}\n        </Text>\n        {!!procedure.synonyms.length && (\n          <>\n            <Text bold style={styles.ProcedureSynonymTitle}>\n              Sin\xc3\xb4nimos\n            </Text>\n            <View style={styles.ProcedureSynonymOptionsContainer}>\n              {procedure.synonyms.map(synonym => <Text style={styles.ProcedureSynonymOption} key={synonym}>{synonym}</Text>)}\n            </View>\n          </>\n        )}\n      </ArrowBox>\n    ))}\n</ScrollView>\n
Run Code Online (Sandbox Code Playgroud)\n

问题是我加载了 API 的整个返回结果,速度变慢了。

\n

我想知道当我到达页面末尾时如何动态加载内容并在 api 中进行新的调用。\nApi 允许我放置偏移量和限制。

\n

有人可以给我一些例子吗?

\n

谢谢!!!!!

\n

Pro*_*eli 6

基本上,ScrollView 并不是设计用来处理动态数据的,设计用来执行此功能的正确组件称为 Flatlist。它的工作方式几乎与 ScrollView 完全相同,但速度更快,并且只会渲染屏幕上显示的组件。

\n

请像这样从 React Native 导入 Flatlist...

\n

\r\n
\r\n
//At the top of your file, please import FlatList together with all the modules that you want\nimport { FlatList, Text, View } from "react-native";
Run Code Online (Sandbox Code Playgroud)\r\n
\r\n
\r\n

\n

然后将代码中的整个 ScrollView 替换为 Flatlist,如下所示:

\n

\r\n
\r\n
<FlatList\n  keyExtractor={(procedure) => procedure.id}\n  data={this.state.procedures}\n  renderItem={(procedure) => {\n    return (\n      <ArrowBox\n        key={procedure.id}\n        onPress={() =>\n          RootNavigation.navigate("ProcedureDetails", {\n          procedure })}>\n            <Text bold style={styles.ProcedureTitle}>\n          {procedure.name}\n        </Text>\n        {!!procedure.synonyms.length && (\n          <>\n            <Text bold style={styles.ProcedureSynonymTitle}>\n              Sin\xc3\xb4nimos\n            </Text>\n            <View\n            style={styles.ProcedureSynonymOptionsContainer}>\n              {procedure.synonyms.map((synonym) => (\n                <Text\n                  style={styles.ProcedureSynonymOption}\n                  key={synonym}>\n                  {synonym}\n                </Text>\n              ))}\n            </View>\n          </>\n        )}\n      </ArrowBox>\n    );\n  }}\n></FlatList>;
Run Code Online (Sandbox Code Playgroud)\r\n
\r\n
\r\n

\n