簡體   English   中英

如何避免在React Component中使用事件偵聽器進行無限重新渲染?

[英]How to avoid infinite re-rendering with event listener in React Component?

我有一個React / Electron應用程序。 我需要從main.js中獲取一些數據庫表,並且需要將狀態設置為該表。

為此,我編寫了以下偵聽器:

ipcRenderer.on('sendTable', (evt, arg) => {
  this.props.setTable(arg);
});

它等待main.js發送“ sendTable”事件,並將表作為參數。 然后,我將Redux存儲設置為該表。 這種作品。

但是,我不知道將這個偵聽器放在哪里。 如果將其放在組件的構造函數或渲染函數中,則會導致無限循環。 但是我需要設置一次,因為我確實需要聽。 我可以放在哪里?

它是附加在一個事件偵聽一個很好的做法componentDidMount ,並在分離的事件偵聽componentWillUnmount

請參見代碼示例:

class Foobar extends Component {

  componentDidMount() {
    ipcRenderer.on('sendTable', (evt, arg) => {
      this.props.setTable(arg);
     });
  }

  componentWillUnmount() {
    // Make sure to remove the DOM listener when the component is unmounted
    // read the ipcMain documentation to understand how to attach and detach listeners
    ipcMain.removeListener(channel, listener)
  }

  render() {
   // stuff
  }

}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM