[英]How to prevent multiplication of ipcRenderer listenters?
我的 React 應用程序中有一個按鈕,每次單擊它都需要執行 1 次操作。 當前,單擊時,聽眾似乎成倍增加。
這是我正在使用的代碼的簡要示例:
// In App.js
const App = () => {
const buttonHandler = () => {
api.myApi.rendererToMain();
api.myApi.mainToRenderer();
};
return (
<div>
<Button cb={buttonHandler} />
</div>
);
};
// In Button.js
const Button = (props) => {
return (
<button type="button" onClick={ (e) => { props.cb() }}>Send Ping</button>
)
};
// In main.js
ipcMain.on('async', (e, msg) => {
console.log(msg); // print ping
e.reply('async_response', 'pong');
});
// In preload.js
contextBridge.exposeInMainWorld('api', {
myApi: {
rendererToMain: () => {
ipcRenderer.send('async', 'ping');
},
mainToRenderer: () => {
ipcRenderer.on('async_response', (e, msg) => {
console.log(msg);
});
},
},
});
當我運行 electron 應用程序時,我打開了主進程的終端,並從渲染器打開了 output 的 devTools。 目前,當按鈕被按下 3 次時,結果如下所示:
// In the browserWindow devTools console
pong
(2)pong
(5)pong
// In the Main process console
ping
ping
ping
所需的 output 僅與渲染器控制台不同:
pong
pong
pong
我嘗試的解決方案
在對 stackoverflow 進行一些研究之后,我第一次嘗試自己解決這個問題是嘗試刪除“async_response”通道的 ipcRenderer 偵聽器。 執行此操作的所有嘗試都不會在渲染器控制台中產生 output,並且在主進程控制台中產生所有 3 個預期的 ping。
例如:
// Change made in preload.js
contextBridge.exposeInMainWorld('api', {
myApi: {
rendererToMain: () => {
ipcRenderer.send('async', 'ping');
},
mainToRenderer: () => {
ipcRenderer.on('async_response', (e, msg) => {
console.log(msg); // With below change, this does nothing.
});
// Attempt to remove the listener now?
// Seems to remove the listener before any output logged.
ipcRenderer.removeAllListeners('async_response');
},
},
});
如果有人能幫助我了解在哪里以及如何阻止聽眾的增加,我將永遠感激不已。 先感謝您。
睡了一會后,我意識到我的搜索范圍太窄了。 我發現每次按下按鈕時都會額外訂閱ipcRenderer.on()
方法,按照這篇文章中的概念: Node.on method firing too many times
了解這一點后,我對我的代碼進行了以下更改,以便對ipcRenderer.on()
方法的調用只發生一次:
// In App.js
const App = () => {
const buttonHandler = () => {
api.myApi.rendererToMain();
// api.myApi.mainToRenderer(); <- Removed this call to the ipcRenderer.on()
};
return (
<div>
<Button cb={buttonHandler} />
</div>
);
};
// In Button.js
const Button = (props) => {
const callbackHandler = () => {
props.cb();
};
// Subscribe to listener on component construction
api.myApi.mainToRenderer();
return (
<button type="button" onClick={ (e) => { callbackHandler() }}>Send Ping</button>
)
};
這些更改會導致完全符合預期的行為。 單擊按鈕三下后,我在渲染器控制台中看到:
(3)pong
暫時不回答這個問題。 我絕對樂於接受有關我的修復和實施的評論。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.