我已经为此苦苦挣扎了太久了。我有一个 Node 服务器,带有 websockets 向 React 客户端发送消息和从 React 客户端接收消息。但出于某种原因,每当从 Node 发送 websocket 消息时,它都会导致所有 React 客户端刷新其顶级组件。因此,如果有人在客户端处理某事,就会把他们搞得一团糟。我什至不知道如何判断这是我的 Node 代码还是 React 代码或两者的问题。
React 代码非常庞大,如果不是必须的话,我不想深入下去。所以我将从我的节点服务器发布 websocket 代码,希望有人能在那里找到一些东西。如果您也需要查看一些 React 代码,可以告诉我。但我希望这只是一个 Node WS 问题。
我的 React 中确实有代码“接收”Node 消息并适当地处理它们,但我注释掉了该代码并且我仍然遇到刷新问题。对此的任何帮助将不胜感激!
更新:在评论中 Daniele 的帮助下,我发现实际上是客户端代码接收了导致刷新的消息。注释掉该代码后,没有刷新发生。
这是我的顶级组件中直接从 app.js 加载的代码:
const ws = useGlobalWebSocketContext();
const numberClients = parseInt(
useGlobalWSDataContext().numberClients,
10
);
const numberIpads = parseInt(
useGlobalWSDataContext().numberIpads,
10
);
console.log('SchedulePage numberIpads: ' + numberIpads);
实际上,我删除了除第一行以外的所有内容,但刷新仍然发生了!
所以我想你们可能都想看看网络套接字上下文文件。
import React, { createContext, useContext } from 'react';
import PropTypes from 'prop-types';
import useWebSocketLite from '../components/home/webSocketHook';
const GlobalWebSocketContext = createContext();
export const useGlobalWebSocketContext = () =>
useContext(GlobalWebSocketContext);
// websocket stuff
const wsURL =
process.env.NODE_ENV === 'development'
? 'ws://localhost'
: 'ws://production.app.local';
const GlobalWebSocketContextProvider = (props) => {
const websocket = useWebSocketLite({
socketUrl: wsURL + ':' + process.env.REACT_APP_WS_PORT
});
return (
<GlobalWebSocketContext.Provider value={websocket}>
{props.children}
</GlobalWebSocketContext.Provider>
);
};