ipcRenderer in React component constructor

…衆ロ難τιáo~ 提交于 2019-12-07 07:07:14

问题


I have an app using Electron, React, and React Router. I'm using ipcRenderer in the component constructor to send events from my component to the main Electron process. After I added React Router to the mix, I noticed that my ipcRenderer event was getting added again and again each time I left and came back to the component. I figure it's because React Router is mounting and unmounting the component as needed.

I found a way around the issue by checking if the event already has been registered like this:

if (!ipcRenderer._events['open-file-reply']) {
  ipcRenderer.on('open-file-reply', (event, fileContents) => {
    if(fileContents){
      this.setState({
        data: JSON.parse(fileContents)
      }); 
    }   
  }); 
} 

I'm just wondering if there is a more correct way to do this. Does ipcRenderer.on belong in the constructor anyway, or is there a more appropriate place to put it?

EDIT

This is the best solution I've come up with so far:

import {ipcRenderer} from  'electron';

/* inside React component */
constructor(props) {
  super(props);
  // ...
  this.loadFileListener = this.loadFileListener.bind(this);
  ipcRenderer.on('open-file-reply', this.loadFileListener);
}

componentWillUnmount() {
  ipcRenderer.removeAllListeners(['open-file-reply']);
}

loadFileListener(event, fileContents) {
  // set state and stuff...
}

回答1:


I don't think you should be setting up IPC until the component is mounted, so I would suggest this approach:

 constructor(props) {
   super(props)
   this._loadFileListener = this._loadFileListener.bind(this)
 }

 componentDidMount() {
   ipcRenderer.on('open-file-reply', this._loadFileListener)
 }

 componentWillUnmount() {
   ipcRenderer.removeListener('open-file-reply', this._loadFileListener)
 }


来源:https://stackoverflow.com/questions/41156945/ipcrenderer-in-react-component-constructor

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!