第七色在线视频,2021少妇久久久久久久久久,亚洲欧洲精品成人久久av18,亚洲国产精品特色大片观看完整版,孙宇晨将参加特朗普的晚宴

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

當彈出窗口關閉時,如何刪除擴展彈出窗口(React 組件)的偵聽器?

當彈出窗口關閉時,如何刪除擴展彈出窗口(React 組件)的偵聽器?

慕運維8079593 2021-12-23 16:21:33
我有一個使用 react(遺留代碼)構建的擴展,并且我一直在跟蹤一個我最終解決的錯誤,但我無法修復。當擴展的圖標(在瀏覽器欄中)被點擊時,一個 reactComponent被創(chuàng)建,并且一個監(jiān)聽器被添加到它的componentDidMount():async componentDidMount(){   ...   // an object from the background is retrieved   let background_object = this.props.getBackgroundObject();   ...   // code including await background_object.doSomething();   ...   // add event (eventemitter3 is used for the event management)   background_object.event.on('onMusic', this.dance);   ...}async dance() {  this.setState({    'music': true,  })}但是,我無法弄清楚如何在Component消失后刪除偵聽器,例如通過單擊瀏覽器中的其他位置。我以為這componentWillUnmount就是我要找的東西,但它從未被稱為:componentWillUnmount(){  // this is never called!!!  background_object.event.removeListener('onDance', this.dance);}問題是,每次我打開(和關閉)擴展彈出窗口時,都會向 中添加一個新事件background_object,因此會dance()多次調用(與打開和關閉彈出窗口一樣多)。現(xiàn)在,我使用了once代替on:async componentDidMount(){   ...   // an object from the background is retrieved   let background_object = this.props.getBackgroundObject();   ...   // code including await background_object.doSomething();   ...   // add event (eventemitter3 is used for the event management)   background_object.event.once('onMusic', this.dance);   ...}async dance() { // add the event again in case onMusic is called again background_object.event.once('onMusic', this.dance); this.setState({   'music': true, })}這樣,至少,它只被調用了一次。但是,我擔心我的組件被多次創(chuàng)建并消耗瀏覽器中的內存。我如何確保組件實際上正在被銷毀?如何檢測彈出窗口何時關閉以刪除事件?
查看完整描述

1 回答

?
收到一只叮咚

TA貢獻1821條經(jīng)驗 獲得超5個贊

可以為此使用chrome.runtime.onConnect(感謝@wOxxOm):


在 React 組件的構造函數(shù)中打開一個連接:

  constructor(props){

    super(props)

    this.state = {

      dance: false,

    }

    ...

    var port = this.xbrowser.runtime.connect();

    ...

  }


componentDidMount在反應組件中添加事件。

async componentDidMount(){

   ...

   // an object from the background is retrieved

   let background_object = this.props.getBackgroundObject();


   ...

   // add event (eventemitter3 is used for the event management)

   background_object.event.on('onMusic', this.dance);

   ...

}


async dance() {

  this.setState({

    'music': true,

  })

}

在后臺的某個地方(例如background.js)偵聽與瀏覽器的連接,并在連接丟失時刪除該事件:

chrome.runtime.onConnect.addListener(function (externalPort) {

  externalPort.onDisconnect.addListener(function () {

     let background_object = this.props.getBackgroundObject();

     background_object.event.removeListener('onSend'); 

  })

})

在我看來,這不是很優(yōu)雅,但它確實有效。


查看完整回答
反對 回復 2021-12-23
  • 1 回答
  • 0 關注
  • 173 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯(lián)系客服咨詢優(yōu)惠詳情

幫助反饋 APP下載

慕課網(wǎng)APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網(wǎng)微信公眾號