2016-12-15 38 views
1

我有一个使用Electron,React和React Router的应用程序。我在组件构造函数中使用ipcRenderer将事件从我的组件发送到主Electron进程。在我添加了React Router之后,我注意到我的ipcRenderer事件每次离开并回到组件后都会一次又一次地被添加。我认为这是因为React Router根据需要安装和卸载组件。React组件构造函数中的ipcRenderer

我找到了解决这一问题的方式通过,如果该事件已经被注册这样的检查:

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

我只是想知道是否有这样做一个比较正确的做法。无论如何,ipcRenderer.on属于构造函数,还是有更合适的地方放置它?

编辑

这是最好的解决方案,我想出来的,到目前为止:

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... 
} 

回答

2

直到组件被安装,我不认为你应该建立IPC,所以我会建议这种方法:

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) 
}