我有一个按钮,在我的反应应用程序,需要做一些事情,每次它被点击。当前,当单击时,侦听器似乎会成倍增加。
下面是我正在使用的代码的简短示例:
// 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);
});
},
},
});当我运行电子应用程序时,我有一个主进程打开的终端,而devTools打开用于从渲染器输出。目前,当按3次按钮时,结果如下:
// In the browserWindow devTools console
pong
(2)pong
(5)pong
// In the Main process console
ping
ping
ping仅对渲染器控制台而言,所需的输出不同:
pong
pong
pong我尝试的解决方案
在进行了一些堆栈溢出研究之后,我自己解决这个问题的第一次尝试是尝试删除“ipcRenderer”通道的async_response侦听器。所有这样做的尝试都导致渲染器控制台中没有输出,主进程控制台中的所有3个预期的pings都没有输出。
例如:
// 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');
},
},
});如果有人能帮助我理解在哪里以及如何阻止听众的繁衍,我将永远感激。提前谢谢你。
发布于 2021-10-05 13:42:44
睡了一会儿后,我意识到我的搜索范围太窄了。我发现,每次按下按钮时,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暂时不回答这个问题。我肯定对我的修复和实现的所有评论是开放的。
https://stackoverflow.com/questions/69444055
复制相似问题