REACT-多用效应中的种族条件清理功能
我有一个组件,可以
- 在MOUNT上启动WebSocket Ref(
endpoint
prop不会更改)。 - 当组件进入屏幕视图时,它调用
subscribe
onwsref << /code>
- 当组件删除屏幕视图时,它调用
unsubscribe
onwsref
问题是在uncount> uncount
上,第二个清理功能失败了,因为我们已经通过第一个清理功能关闭了Websocket。
因此,我们无法退缩
,因为Websocket不在open
状态中。
如何控制这里的清理效果顺序?
function Comp({endpoint, isVisible, id}) {
const wsRef = useRef(null);
useEffect(() => {
wsRef.current = new WebsocketClass(endpoint);
return () => { // [1] cleanup no 1
wsRef.current.close();
wsRef.current = null;
}
}, [endpoint]);
useEffect(() => {
if (isVisible) {
wsRef.current.subscribe(id);
}
return () => {
if (isVisible) {
wsRef.current.unsubscribe(id); // [2] fails, this cleanup runs after [1]
}
}
}, [isVisible, id]);
}
如果我在功能中重新订购两个使用效果
,问题似乎消失了,但是这里真的是一个永久的解决方案吗?
另外,我不能关闭
unbubscribe
清理中的Websocket,因为该组件可以在屏幕上熄灭时保持安装并在用户来回滚动时再次返回。
I have a component that
- Initiate a websocket ref on mount (
endpoint
prop doesn't change) - When component comes into screen view, it calls the
subscribe
onwsRef
- When component goes out of screen view, it calls the
unsubscribe
onwsRef
The problem is on unmount
the 2nd cleanup function fails because we already have closed the websocket by the 1st cleanup function.
So we are unable to unsubscribe
as the websocket is not in OPEN
state.
How to control the order of cleanup effects here?
function Comp({endpoint, isVisible, id}) {
const wsRef = useRef(null);
useEffect(() => {
wsRef.current = new WebsocketClass(endpoint);
return () => { // [1] cleanup no 1
wsRef.current.close();
wsRef.current = null;
}
}, [endpoint]);
useEffect(() => {
if (isVisible) {
wsRef.current.subscribe(id);
}
return () => {
if (isVisible) {
wsRef.current.unsubscribe(id); // [2] fails, this cleanup runs after [1]
}
}
}, [isVisible, id]);
}
If I re-order the two useEffect
in my function, the problem seem to go away, but is it really a permanent solution here?
Also, I can't close
the websocket in the unsubscribe
cleanup because the component can stay mounted while it goes out of screen and comes back again as user scrolls back and forth.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论