【问题标题】:Maintaining a websocket connection in state with React and Recoil.js使用 React 和 Recoil.js 保持 websocket 连接的状态
【发布时间】:2021-07-12 16:18:23
【问题描述】:

我正在寻找一种实用的方法来使用 Recoil 来维持 websocket 连接。

我的想法是把 websocket 放到一个 atom 中:

import useWebSocket from 'react-use-websocket';
import { atom, selector } from 'recoil';

const socketUrl =
  'wss://xxx.com';

const webSocket = useWebSocket(socketUrl, {
  onOpen: () => console.log('opened'),
  //Will attempt to reconnect on all close events, such as server shutting down
  shouldReconnect: (closeEvent) => true,
});

// If the page has been archived before, the id in the archive
export const webSocketAtom = atom({
  key: 'webSocket',
  default: webSocket,
});

这是一个好方法还是我违反了一些规则?

【问题讨论】:

    标签: reactjs websocket recoiljs


    【解决方案1】:

    Recoil 目前无法处理类实例,这是唯一的规则。

    您的代码当然不起作用,因为您在组件外部使用了钩子,但除此之外,您应该能够将返回的 useWebSocket 对象保存在原子内。

    【讨论】:

      猜你喜欢
      • 2012-01-03
      • 1970-01-01
      • 2018-11-19
      • 1970-01-01
      • 2014-03-19
      • 2017-05-03
      • 2021-06-11
      • 1970-01-01
      • 2019-10-28
      相关资源
      最近更新 更多