[英]What would you suggest as pattern for canceling subscriptions in useEffect hook?
Most of you have probably seen this React warning.你们中的大多数人可能已经看到了这个 React 警告。 Me too, and it is clear to my why React gives warns us about unmounting during a state update.
我也是,我很清楚为什么 React 会在 state 更新期间警告我们卸载。 But I'm trying to figure out what is the best React pattern prevent a possible memory leak.
但我试图弄清楚什么是最好的 React 模式可以防止可能的 memory 泄漏。
Warning: Can't perform a React state update on an unmounted component.
This is a no-op, but it indicates a memory leak in your application.
To fix, cancel all subscriptions and asynchronous tasks in a useEffect cleanup function.
In my projects I'm using this boolean flag didCancel
to let my data fetching logic know about the state of the component.在我的项目中,我使用这个 boolean 标志
didCancel
让我的数据获取逻辑知道组件的 state。 If the component did unmount, the flag should be set to true which results in preventing to set the component state after the data fetching has been asynchronously resolved eventually.如果组件确实卸载,则该标志应设置为 true,这会导致在最终异步解决数据获取后阻止设置组件 state。
useEffect(() => {
let didCancel = false;
const fetchEvents = () => {
fetch(url, settings)
.then(res => {
return res.json();
})
.then(({ data }) => {
if (!didCancel) {
setEvents(data.events);
}
})
.catch(err => {
console.log(err);
if (!didCancel) {
setLoading(false);
}
});
};
fetchEvents();
return () => {
didCancel = true;
};
}, []);
So eventhough this works, I just want to know what you guys are using as a pattern.因此,尽管这可行,但我只想知道你们正在使用什么作为模式。 What could be seen as best practice?
什么可以被视为最佳实践? Is there remarkable difference when fetching data, then when you're only updating state?
获取数据时是否有显着差异,然后仅更新 state? Please let me know!
请告诉我!
I prefer using defer
from rxjs
library for this:我更喜欢为此使用
rxjs
库中的defer
:
useEffect(() => {
const subscription = defer(() =>
fetch(url, settings).then(response => response.json())
).subscribe({
next: ({ data }) => {
setEvents(data.events);
},
error: () => {
setLoading(false);
},
complete: () => {
setLoading(false);
}
});
return () => subscription.unsubscribe();
}, []);
What is didCancel
supposed to be doing? didCancel
应该做什么? It just looks like a local variable you're switching to true on mount.它看起来就像一个局部变量,您在挂载时切换为 true。 Is it used in your
fetchEvents
?它是否在您的
fetchEvents
中使用? Your fetchEvents
will never be called after the initial mount初始挂载后永远不会调用您的
fetchEvents
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.