reactnative 实现一个非常完美的FlatList分页效果
import React, { useState, useEffect, useCallback } from 'react';
import { FlatList, ActivityIndicator, Text, View } from 'react-native';
const ItemSeparatorComponent = () => (
<View
style={{
height: 1,
width: "100%",
backgroundColor: "#ccc",
}}
/>
);
const ListFooterComponent = ({ isLoading }) => {
if (isLoading) {
return (
<View
style={{
paddingVertical: 20,
borderTopWidth: 1,
borderColor: "#ccc"
}}
>
<ActivityIndicator />
</View>
);
}
return null;
};
const App = () => {
const [data, setData] = useState([]);
const [page, setPage] = useState(1);
const [isLoading, setIsLoading] = useState(false);
const [isRefreshing, setIsRefreshing] = useState(false);
const fetchData = useCallback(async () => {
if (isLoading) return;
setIsLoading(true);
try {
const response = await fetch(
`https://api.example.com/data?page=${page}`
);
const newData = await response.json();
setData(page === 1 ? newData : [...data, ...newData]);
setPage(page + 1);
} catch (error) {
console.error(error);
}
setIsLoading(false);
}, [isLoading, page, data]);
useEffect(() => {
fetchData();
}, [fetchData]);
const handleRefresh = useCallback(async () => {
if (isRefreshing) return;
setIsRefreshing(true);
setPage(1);
setData([]);
await fetchData();
setIsRefreshing(false);
}, [fetchData, isRefreshing]);
return (
<FlatList
data={data}
onEndReached={fetchData}
onEndReachedThreshold={0.5}
onRefresh={handleRefresh}
refreshing={isRefreshing}
keyExtractor={item => item.id}
renderItem={({ item }) => (
<View>
<Text>{item.title}</Text>
</View>
)}
ItemSeparatorComponent={ItemSeparatorComponent}
ListFooterComponent={
<ListFooterComponent isLoading={isLoading} />
}
/>
);
};
export default App;
这段代码展示了如何使用React Native的FlatList组件来实现一个基本的分页列表。它使用了useState和useEffect来管理组件的状态,并通过useCallback来避免不必要的重渲染。代码中包含了分页加载数据、下拉刷新,以及加载指示器的例子,是一个很好的学习和实践React Native列表分页的例子。
评论已关闭