首页 > 解决方案 > 如何在 React 函数之外持久化变量?

问题描述

我的目标是避免React.useEffect在每次重新渲染时调用方法。发生这种情况是因为 React 认为stompClient变量在每次重新渲染时都是未定义的。

这是我当前使用的解决方案,但这将导致stompClient在每次重新渲染时重新连接。

应用程序.tsx

import React from "react";
import {stompClient, setStompClient} from "./services/StompClient";

const AuthenticatedContainer = () => {
  ...

  React.useEffect(() => {
    if (stompClient?.connected === undefined || stompClient.connected === false) {
      // this always happens on each re-render, causing unnecessary re-connection.
      setStompClient( the config );
    }
  });

  ....
}

./services/StompClient/index.tsx

import {Client, IFrame, StompConfig} from '@stomp/stompjs';
import {environment} from '../../environments/environment';

export let stompClient: Client | null = null;

export const setStompClient = (
  onConnect: () => void,
  onStompError: (receipt: IFrame) => void,
) => {
  const stompConfig: StompConfig = {
    brokerURL: `${environment.wsBaseURL}/chat`,
    forceBinaryWSFrames: true,
    appendMissingNULLonIncoming: true,
    onConnect,
    onStompError,
  };

  stompClient = new Client(stompConfig);
};

我试过的:

  1. 我试图StompClient用 redux 存储对象。事实证明,redux 不喜欢存储不可序列化的对象。参考
  2. 我试图创建一个自定义钩子,这将创建多个StompClient而不是一个。参考

我没有尝试过的:

  1. 使用 React.Context,我假设 React.Context 和 Redux 是一样的,它不喜欢存储不可序列化的对象。如果我错了,请随时告诉我。

标签: javascriptreactjsreact-nativereact-redux

解决方案


推荐阅读