javascript - 如何在 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);
};
我试过的:
我没有尝试过的:
- 使用 React.Context,我假设 React.Context 和 Redux 是一样的,它不喜欢存储不可序列化的对象。如果我错了,请随时告诉我。
解决方案
推荐阅读
- java - 如果文本字段为空,则禁用 AjaxSubmitButton
- http-headers - sec-fetch-site 标头是什么意思?为什么 Origin 标头未定义?
- microsoft-edge - Edge 浏览器不支持 X-UA-Compatible 元标记中定义的文档模式
- scala - Scala: Alternative for deprecated set difference
- redis - Redis:Redisinsight:连接时出错:“添加数据库时出错。请重试”
- c# - 嵌入式字体在 Windows 7 中不支持“常规”样式,但在 Windows 10 中可以
- angularjs - 在 Angular 应用程序中使用服务器呈现的 html 的解决方法
- node.js - {“message”:“用户未授权”}在nodejs项目中显示
- swiftui - 仅在 View 中输入数据时,获取数据的最佳方法是什么?
- r - 具有 NA 的时间序列的频率(R 软件)