REACT-多用效应中的种族条件清理功能

发布于 2025-01-30 04:20:15 字数 1162 浏览 4 评论 0原文

我有一个组件,可以

  1. 在MOUNT上启动WebSocket Ref(endpoint prop不会更改)。
  2. 当组件进入屏幕视图时,它调用subscribe on wsref << /code>
  3. 当组件删除屏幕视图时,它调用unsubscribe on wsref

问题是在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

  1. Initiate a websocket ref on mount (endpoint prop doesn't change)
  2. When component comes into screen view, it calls the subscribe on wsRef
  3. When component goes out of screen view, it calls the unsubscribe on wsRef

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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。
列表为空,暂无数据
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文