我已經為此苦苦掙扎了太久了。我有一個 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 stuffconst 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> );};
無論何時從 Node WS 服務器發送消息,它都會導致所有 React 客戶端刷新
蕭十郎
2023-01-06 16:24:55