我有一个应用程序使用电子,反应,和反应路由器。我在组件构造函数中使用ipcRenderer将事件从组件发送到主电子进程。在向混合添加了React路由器之后,我注意到每次离开并返回到组件时,我的ipcRenderer事件都会一次又一次地被添加。我想这是因为React路由器正在根据需要安装和卸载组件。
我找到了一个解决这个问题的方法,就是检查事件是否已经像这样注册了:
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...
}发布于 2016-12-15 10:26:23
我认为在安装组件之前不应该设置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)
}https://stackoverflow.com/questions/41156945
复制相似问题