在反应中重新连接 websocket 的最佳实践是什么? [英] What is best practice to websocket reconnect in react?

查看:46
本文介绍了在反应中重新连接 websocket 的最佳实践是什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经通过票务轮询来响应应用程序(票证是 websocket 连接链接的一部分).然后我将 websocket 对象传递给另一个组件,因为只有这个(另一个)组件应该使 .send()用户登录或注销后,我需要为新连接获取新票证,因为服务器具有用于登录用户的专门数据.我应该如何为这个任务组织我的代码?

I have react app with ticket polling (ticket is part of link for websocket connection). Then I pass websocket object to another component, because only this (another) component should make .send() After user login or logout I need to get new ticket for new connection because server has specialized data for logged users. How should I organize my code for this task?

我尝试在登录/注销后重新分配 ws 对象,但收到每次渲染后从 React Hook useEffect 内部对 'ws' 变量的分配将丢失"错误我无法将 ws 分配存储在 useEffect 钩子中,因为那样我就无法将其作为道具传递正如你所看到的,我正在使用 Redux

I tried to reassign ws object after login/logout but got "Assignments to the 'ws' variable from inside React Hook useEffect will be lost after each render" error I can't store ws assignment inside useEffect hook because then i not be able to pass it as prop I'm although using Redux as you can see

const App = () => {
  const { ticket, isLoggedIn } = useSelector(state => state);
  const dispatch = useDispatch();

  useEffect(() => {
    const requestTicket = () => {
      fetch('http://some/api/websocket', {
        method: 'POST'
      })
        .then(response => response.json())
        .then(ticket => {
          dispatch(setTicket(ticket));
        });
    };
    requestTicket();
  }, [dispatch]);

  let ws = new WebSocket('ws://socket/' + ticket);

  useEffect(() => {
    fetch('http://some/api/websocket', {
      method: 'POST'
    })
      .then(response => response.json())
      .then(ticket => {
        ws = new WebSocket('ws://socket/' + ticket);
      });
  }, [isLoggedIn, ws]);

  ws.onmessage = e => {
    dispatch(setData(JSON.parse(e.data)));
  };

  return <Child ws={ws} />;
};

推荐答案

将 WebSocket 连接和 onmessage 包装在一个函数中.检查 WebSocket 是否关闭,回调函数.也可以使用setTimeout.示例:

Wrap WebSocket connection and onmessage in a function. check if WebSocket is close, callback the function. Also may use setTimeout. Example :

function connect(){
  //WebSocket Connection
  //WebSocket onmessage
}
conn.onclose = evt => {
console.log('Socket is closed.Reconnect will be attempted in 10 second.', evt.reason);
    setTimeout(() => connect(), 10000);
};

这篇关于在反应中重新连接 websocket 的最佳实践是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆