2016-12-15 36 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) 
}