简体   繁体   English

在 React Base chrome 扩展中使用长寿命连接时无法获取状态值

[英]Unable to get state value in when using long-lived connection in react base chrome extension

I have a Popup.jsx and a Background.js .我有一个Popup.jsx和一个Background.js The Popup creates a long lived connection to my background service worker.弹出窗口创建了与我的后台服务人员的长期连接

I am maintaining a state in my Popup.jsx , which looks like this我在我的Popup.jsx中保持一个状态,看起来像这样

const [projectDetail, setProjectDetail] = useState({ projectCode: null })

The useEffect of my Popup.jsx looks like this,我的useEffectPopup.jsx看起来像这样,

useEffect(() => {
    port = chrome.runtime.connect({ name: 'Background Connection' })
    port.onMessage.addListener(({ action, payload }) => {

      switch (action) {
        case ACTION.SET_PROJECT_DETAIL:
          setProjectDetail(payload);
          break;
  
        case ACTION.CHECK_STATE:
          console.log(projectDetail)
          break;
   
        
        default:
          break;
      }
  
    })
    port.postMessage({ action: ACTION.GET_PROJECT_DETAIL })
    return () => {
      port.disconnect()
    }
  }, [])

As you can see, after attaching the listener for onMessage on the port variable (which is defined outside the component scope), I am sending a message to the Background.js to get project detail.如您所见,在port变量(定义在组件范围之外)上附加onMessage的侦听器后,我向Background.js发送消息以获取项目详细信息。 The Background.js responds back with as per the following code: Background.js根据以下代码进行响应:

chrome.runtime.onConnect.addListener(function (port) {
  // console.log("🚀 ~ file: index.js ~ line 182 ~ chrome.runtime.onConnect.addListener ~ port", port)

  port.onMessage.addListener(function ({ action, payload }) {

    if (action === ACTION.GET_PROJECT_DETAIL) {
       port.postMessage({ action: ACTION.SET_PROJECT_DETAIL, payload: { projectCode: "Some value"} })
    }

   // ...Removed more code for brevity

  });
});

Assume that I have a user interaction button which tells the Background.js to send a message to the Popup.jsx which matches the case ACTION.CHECK_STATE: , so evidently, I am expecting the Popup.jsx to console log the value {projectCode: "Some value"} as the state in the component has been updated (I have verified that it does by using ReactDevTools ).假设我有一个用户交互按钮,它告诉Background.js向与case ACTION.CHECK_STATE:匹配的Popup.jsx发送一条消息,所以显然,我希望Popup.jsx控制台记录值{projectCode: "Some value"}作为组件中的状态已更新(我已经通过使用ReactDevTools验证了它确实如此)。

However, it prints { projectCode: null } which was the initial state value.但是,它会打印{ projectCode: null }这是初始状态值。

Note: the user interaction does not happen immediately after the component mounts, so its not that I am trying to get the state value immediately after I have set it.注意:用户交互不会在组件挂载后立即发生,所以并不是我在设置后立即尝试获取状态值。

I am unable to get the updated state value inside the callback function for addListener .我无法在addListener的回调函数中获取更新的状态值。 Not sure what am I doing wrong here.不知道我在这里做错了什么。

The reason it was not working was that the port variable was declared outside the functional component itself.它不起作用的原因是port变量是在功能组件本身之外声明的。

Initially, the Popup.jsx was defined like this,最初, Popup.jsx是这样定义的,

//...import statements

let port = null;
const Popup = () => {
  port = chrome.runtime.connect({ name: 'Background Connection' });
  
  //...more code
}

Afterwards, I changed it into,后来我改成

//...import statements

const Popup = () => {
  let port = chrome.runtime.connect({ name: 'Background Connection' });
  
  //...more code
}

I can't say specifically what exactly was the reason.具体是什么原因我不能说。 However, it seems to me that it was scoping issue.但是,在我看来,这是范围界定问题。

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

相关问题 Chrome扩展程序的长期消息连接-如何使用回调函数? - Chrome extension long-lived message connection - how to use callback functions? chrome扩展中具有长期连接的“尝试使用断开连接的端口对象” - “Attempting to use a disconnected port object” with Long-lived connections in chrome extension Chrome扩展程序的长期连接:从后台检索消息到内容 - Chrome extension long lived connection: retrieve message from background to content 如何建立与jQuery的长期连接以进行推送通知? - How can I establish a long-lived connection with jQuery for push notification? Facebook 图 API 长寿命令牌 - Facebook Graph API Long-Lived Token 将短期访问令牌交换为长期有效 - Exchange short-lived access token for long-lived, not working 如何在浏览器中获取JS代码的长期身份提供者令牌 - How to get long-lived indentity provider tokens for JS code in browser Background.js 到 content.js 使用端口和长寿命消息传递 - Background.js to content.js using Port & Long-lived messaging 使用Apache / PHP / Javascript的长期连接(异步服务器推送)? - Long-lived connections (asynchronous server push) with Apache/PHP/Javascript? Recoil:将长期存在的客户端 object 传递给选择器 - Recoil: Passing a long-lived client object to a selector
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM