简体   繁体   English

访问记忆函数中更新的上下文

[英]Access to updated context inside memoized function

I created a component (for websocket communication, as a react context) that needs to access to my AppContext component.我创建了一个需要访问我的 AppContext 组件的组件(用于 websocket 通信,作为反应上下文)。

The WebSocketContext component makes use of useCallback and useMemo , so that the websocket connection is not alway re-created on every re-render of AppContext. WebSocketContext 组件使用useCallbackuseMemo ,因此每次重新渲染 AppContext 时都不会重新创建 websocket 连接。

What I cannot figure out is why I cannot access to the current value of appContext when .onmessage executes.我无法弄清楚为什么在.onmessage执行时我无法访问 appContext 的当前值。 Basically, what I get is the initial value of appContext.基本上,我得到的是appContext的初始值。

What can I do to get the current value ?我该怎么做才能获得当前值?

App.js应用程序.js

<AppContext>
  <WebSocketProvider>
    ...

WebSocketContext.js WebSocketContext.js

import React, { useEffect, useContext, useCallback, useMemo, useState }  from 'react';
import { w3cwebsocket as W3CWebSocket } from "websocket";
import { AppContext } from "./AppContext.js";

export const WebSocketContext = React.createContext(null);

const WebSocketProvider = ({ children }) => {

  const [appContext, setAppContext] = useContext(AppContext);  
  const [wsClient, setWsClient] = useState(null);

  const sendMessage = useCallback((message) => {
    wsClient.send(message);
  });

  const connect = useCallback(() => {

    console.log(Date.now(), appContext.activeZone); //access to current value of appContext is OK

    let tmpWsClient = new W3CWebSocket("wss://127.0.0.1:5000");

    tmpWsClient.onmessage = (message) => {   
      const msgObj = JSON.parse(message.data);      
      console.log("[Message received!]", Date.now(), appContext.activeZone); //not the current value of appContext! (actually, the initial value)
    };    
    tmpWsClient.onopen = (event) => { ... };
    tmpWsClient.onclose = (event) => { ... };
    tmpWsClient.onerror = (err) => { ... };

    return tmpWsClient;
  });

  //at 1st render of the component, create websocket client
  useEffect(() => {
    if (!wsClient) {
      const tmpWsClient = connect();
      //set websocket context
      setWsClient(tmpWsClient);
    }
  }, []);

  //this triggers as expected
  useEffect(() => {
    console.log("activeZone change detected:", appContext.activeZone);//access to current value of appContext is OK
  }, [appContext.activeZone]);

  const contextValue = useMemo(
    () => ({
    client: wsClient, 
    sendMessage
  }), [wsClient, sendMessage]);

  return (
    <WebSocketContext.Provider value={contextValue}>
        {children}
    </WebSocketContext.Provider>
  );
};

const context = ({children}) => WebSocketProvider({children}); 
export default context;

What you have to do in connect is to set in you useCallBack the data needed to update the memorized function whenever is needed您在connect中要做的就是在您的 useCallBack 中设置在需要时更新记忆函数所需的数据

const connect = useCallback(() => {

    console.log(Date.now(), appContext.activeZone); 
    let tmpWsClient = new W3CWebSocket("wss://127.0.0.1:5000");

    tmpWsClient.onmessage = (message) => {   
      const msgObj = JSON.parse(message.data);      
      console.log("[Message received!]", Date.now(), appContext.activeZone); 
(actually, the initial value)
    };    
    tmpWsClient.onopen = (event) => { ... };
    tmpWsClient.onclose = (event) => { ... };
    tmpWsClient.onerror = (err) => { ... };

    return tmpWsClient;
  },[appContext]);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM