[英]useEffect with recyclerlistview (React Native) and exhaustive-deps
I am using a useEffect to fetch data on component render and set it to React Native RecyclerView as a data provider.我正在使用 useEffect 来获取组件渲染上的数据并将其设置为 React Native RecyclerView 作为数据提供者。 I then set the state locally by appending to the existing dataProviderState.
然后我通过附加到现有的 dataProviderState 在本地设置 state。 The problem is when I add the state as a dependency to the array the performance is terrible, as now the useEffect is called every time the list changes, so whenever the list is scrolled.
问题是当我将 state 添加为数组的依赖项时,性能很糟糕,因为现在每次列表更改时都会调用 useEffect,因此每当滚动列表时。 How can I rewrite this hook to make this more performant while also following the exhaustive deps rule?
如何在遵循详尽的 deps 规则的同时重写这个钩子以提高性能?
const dataProvider = new DataProvider((r1, r2) => r1 !== r2);
const rows = dataProvider.cloneWithRows([]);
const [dataProviderState, setDataProviderState] = useState(rows);
useEffect(() => {
const handleFetchContacts = async () => {
try {
const fetchedContacts = await fetchContacts();
setContacts(fetchedContacts);
setDataProviderState(dataProviderState.cloneWithRows(fetchedContacts));
} catch (error) {
logger.error(error);
}
};
const requestPermissionAndFetchContacts = async () => {
try {
const permission = await requestPermissionToContacts();
setPermissions({contacts: permission});
if (permission) {
handleFetchContacts();
}
} catch (err) {
logger.error(err);
setTimeout(() => requestPermissionAndFetchContacts(), 2000);
}
};
requestPermissionAndFetchContacts();
}, [handleFetchContacts]);
^adding dataProviderState to the dependency array here makes the list slow ^在此处将 dataProviderState 添加到依赖数组会使列表变慢
I was able to fix this by referencing the previous state in the callback, so exhaustive-deps stopped complaining about me referencing the state value directly inside the component, but not having it in the array:我可以通过在回调中引用之前的 state 来解决此问题,因此详尽的部门不再抱怨我直接在组件内部引用 state 值,但没有在数组中包含它:
setDataProviderState(state => state.cloneWithRows(fetchedContacts));
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.