如何正确使用钩子? [英] How to use hooks in correct way?
问题描述
我有问题
1- 我定义了一个从 API 获取数据并在 useEffect
中调用它的函数,它运行良好但是我在 VScode 中收到了这个警告.
1- I defined a function that gets data from API and calling it in useEffect
, It's work well
But i got this warning in VScode.
React Hook React.useEffect 缺少依赖项:'getOpenOrders'.包括它或删除依赖项数组.
React Hook React.useEffect has a missing dependency: 'getOpenOrders'. Either include it or remove the dependency array.
2- 我在 FlatList 中实现分页,所以当用户到达数据列表的末尾时,我调用一个函数来增加当前页面,并根据当前页面更新,再次获取 getOpenOrders
因为我将 currentPage
传递给 useEffect 到依赖数组
2- I implement pagination in the FlatList, So when the user reached the end of data List I calling a function to increment the current page, and based on current page updated, getOpenOrders
fetched again because i pass currentPage
to useEffect to the dependency array
所以这里的问题是 getOpenOrders
应该用新数据联系以前的数据,所以我使用 Concat
方法,
So the issue here is in getOpenOrders
should be contacted previous data with the new data so I use Concat
method,
它运行良好但有一段时间我收到警告,告诉我有重复的数据,当我使用 spread [...old, new]
时,我遇到了一个大错误,因为 Flatlist keyExtractor 问题或其他问题,
It's work well But some time I got a warning tells me there an duplicated data,
And when I use spread [...old, new]
not work and I got a big error because Flatlist keyExtractor issue or something,
那么这里的任何英雄都可以查看我的代码并告诉我问题 1 - 2
So can any hero here review my code and tell me what the wrong here with issue 1 - 2
代码片段
const OpenedAppointments = () => {
const [openedAppointment, setOpenedAppointment] = useState([]);
const [currentPage, setCurrentPage] = useState(1);
const [lastPage, setLastPage] = useState(1);
const [loading, setLoading] = useState(false);
const [isFetch, setIsFetch] = useState(false);
const loadMoreOrders = () => {
if (currentPage <= lastPage - 1) {
setLoading(true);
setCurrentPage((prevPage) => prevPage + 1);
console.log('loadMore??');
}
};
const _renderFooter = () => {
return loading ? (
<View
style={{
paddingVertical: 10,
}}>
<ActivityIndicator color="#000000" size="large" />
</View>
) : null;
};
const getOpenOrders = () => {
let AuthStr =
'Bearer ,,,,';
const headers = {
'Content-Type': 'application/json',
Authorization: AuthStr,
};
Api.post(
`/open_orders?page=${currentPage}`,
{},
{
headers,
},
)
.then((res) => {
let last_Page = res.data.open_orders.last_page;
let allOpenedOrders = res.data.open_orders.data;
console.log('res:', allOpenedOrders);
console.log('last_Page', last_Page);
setLastPage(last_Page);
setOpenedAppointment((prevOpenedOrders) =>
prevOpenedOrders.concat(allOpenedOrders),
); // issue 2
// setOpenedAppointment((prevOpenedOrders) =>[...prevOpenedOrders, allOpenedOrders]);
setLoading(false);
// For pull to refresh
setIsFetch(false);
})
.catch((err) => console.log('err', err));
};
// For pull to refresh
const _refresh = () => {
setIsFetch(true);
getOpenOrders();
};
React.useEffect(() => {
getOpenOrders();
}, [currentPage]); // warning here "issue 1"
return (
<FlatList
showsVerticalScrollIndicator={false}
contentContainerStyle={{flexGrow: 1}}
data={openedAppointment}
ListEmptyComponent={renderEmpty}
renderItem={renderItems}
keyExtractor={(item,index) => String(index)}
ListFooterComponent={_renderFooter}
onEndReached={loadMoreOrders}
onEndReachedThreshold={1}
// For pull to refresh
onRefresh={_refresh}
refreshing={isFetch}
/>
);
};
export default OpenedAppointments;
推荐答案
对于问题 1:
要么将依赖项添加到数组中:
either add the dependency to the array:
React.useEffect(() => {
getOpenOrders();
}, [currentPage, getOpenOrders]);
或使用@Matt Aft 回答的 eslint 规则,它不会对您的用例产生影响
or use eslint rule as answered by @Matt Aft, It wont make a difference for your usecase
对于问题 2:我建议使用 Set 删除重复项:
For issue 2: I would suggest removing duplicates with a Set:
setOpenedAppointment((prevOpenedOrders) =>
Array.from(new Set([...prevOpenedOrders, ...allOpenedOrders]))
);
这将使用价差语法 (...) 连接您的新订单和旧订单,并通过创建新集合来删除重复项.(集合只允许唯一的项目,因此会删除重复项.然后你用 Array.from 将它转换回一个数组,这样你就可以像以前一样使用它
This will concat your new Orders and your old Orders with spread syntax (...) and will remove duplicates by creating a new Set. (Sets allow only unique items, therefore will remove duplicates. Then you convert it back to an Array with Array.from so you can use it as before
这篇关于如何正确使用钩子?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!