亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

無論何時從 Node WS 服務器發送消息,它都會導致所有 React 客戶端刷新

無論何時從 Node WS 服務器發送消息,它都會導致所有 React 客戶端刷新

蕭十郎 2023-01-06 16:24:55
我已經為此苦苦掙扎了太久了。我有一個 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>    );};
查看完整描述

1 回答

?
青春有我

TA貢獻1784條經驗 獲得超8個贊

每次接收到新數據時ws.onmessage都會調用 which 又會調用setDatawhich changes the state,如果useGlobalWebSocketContext在頂級組件中使用,那么這個組件將重新渲染是正常的



查看完整回答
反對 回復 2023-01-06
  • 1 回答
  • 0 關注
  • 150 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號