【发布时间】:2022-11-03 01:53:43
【问题描述】:
你好互联网上的好人。我正在尝试实现一个具有拉刷新和分页功能的平面列表,但是我遇到了问题,尤其是拉刷新项目。这是我的代码
const [page, setPage] = useState(1);
const [loading, setLoading] = useState(false);
const [hasnextpage, setHasNextPage] = useState(true);
const [refresh, setRefresh] = useState(false);
const { refreshing } = useContext(ExtrasContext);//called after an order has been processed so as to fetch latest products
const products = useSelector((state) => state?.products?.products);//get products from redux
从 api 获取产品
const getAllproducts = async () => {
console.log(page);//logging the current page here...
if (!loading && hasnextpage) { //hasnextpage set to true and is updated from api !loading ensures i dont call the function when the app is in loading state
setLoading(true);
try {
const response = await axiosprivate.get(
`bp_employee_get_all_products_information?page=${page}`,
{
headers: { Authorization: "Bearer " + auth?.accessToken },
}
);
console.log(response);
if (response?.data?.status === 200) {
console.log(response?.data?.data);
setHasNextPage(response?.data?.data?.hasNextPage); //returns true/false depending on data from the api
const maxpage = response?.data?.data?.totalPages;//returns total pages in the api and guides me not to fetch more items if it reaches last page
if ((page < maxpage )) {
setPage((prev) => prev + 1);
console.log("i was added");
}
dispatch(addProducts([...products, ...response?.data?.data.docs])); //add all products to redux state
setLoading(false);
} else {
console.log("error found");
setLoading(false);
}
} catch (error) {
console.log(error);
setLoading(false);
}
} else return;
在下面的 clearproductlist 中,我重置了所有内容,因此我将页面设置为一个,但是当我拉动刷新并且当我在 getAllProducts 函数上注销当前页面时,它不会重置为 1。这就是我认为问题所在 我还将 setHasNextPage 状态重置为原始状态,然后清除保存产品的 redux 状态
const clearproductlist = () => {
setPage(prev=>prev=1);//i tried setPage(1) didnt work. How do i reset this state?
setHasNextPage(true);
dispatch(clearProduct()); Clears everything in redux products state
};
如上所示,我重置一切
此功能在我下拉刷新时运行
const Refresh = () => {
clearproductlist();
setRefresh(true);
getAllproducts();
setRefresh(false);
};
当订单/交易发生时调用下面的使用效果,我这样做是为了获取新项目,因为它们在后端
useEffect(() => {
if (refreshing && refreshing) {
Refresh();
console.log("i run");
}
}, [refreshing]);
下面是我的平面列表组件
return (
<FlatList
keyExtractor={keyExtractor}
data={products}
renderItem={renderItem}
numColumns={viewchange === true ? 1 : 2}
key={viewchange === true ? 1 : 2}
onEndReachedThreshold={0.7}
maxToRenderPerBatch={10}
estimatedItemSize={50}
onEndReached={getAllproducts}
refreshing={refresh}
onRefresh={Refresh}
contentContainerStyle={{
justifyContent: "space-between",
paddingBottom: 100,
}}
ListFooterComponent={
loading && (
<View style={{ alignItems: "center" }}>
<ActivityIndicator size="large" color="#0000ff" />
</View>
)
}
showsVerticalScrollIndicator={false}
/>
)}
)
一切正常,除了拉刷新。当我拉动刷新时,它不会重置当前页面,因此它会获取页面状态,即 2 而不是 1,因此会加载我不想要的项目。任何帮助将不胜感激
【问题讨论】:
标签: react-native react-hooks state react-native-flatlist pull-to-refresh