React 组件构造函数中的 ipcRenderer [英] ipcRenderer in React component constructor
问题描述
我有一个使用 Electron、React 和 React Router 的应用程序.我在组件构造函数中使用 ipcRenderer
将事件从我的组件发送到主 Electron 进程.在我将 React Router 添加到组合中后,我注意到我的 ipcRenderer 事件每次我离开并返回组件时都会一次又一次地添加.我认为这是因为 React Router 正在根据需要安装和卸载组件.
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)
});
}
});
}
我只是想知道是否有更正确的方法可以做到这一点.ipcRenderer.on
到底属于构造函数,还是有更合适的地方放?
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?
编辑
这是迄今为止我想出的最佳解决方案:
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...
}
推荐答案
我不认为你应该在安装组件之前设置 IPC,所以我建议这种方法:
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)
}
这篇关于React 组件构造函数中的 ipcRenderer的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!