我有一个 React/Electron 应用程序。我需要从 main.js 获取一些数据库表,并且需要将状态设置到该表。
为此,我编写了以下监听器:
ipcRenderer.on('sendTable', (evt, arg) => {
this.props.setTable(arg);
});
它等待 main.js 发送“sendTable”事件,并以表作为参数。然后,我将 Redux 存储设置到该表。 这种作品。
但是,我不知道将该监听器放在哪里。如果我将它放在组件的构造函数或渲染函数中,我最终会陷入无限循环。但我需要设置一次,因为我确实需要倾听。我可以把它放在哪里?
最佳答案
最好在 componentDidMount
中附加事件监听器,并在 componentWillUnmount
中分离事件监听器!
查看代码示例:
class Foobar extends Component {
componentDidMount() {
ipcRenderer.on('sendTable', (evt, arg) => {
this.props.setTable(arg);
});
}
componentWillUnmount() {
// Make sure to remove the DOM listener when the component is unmounted
// read the ipcMain documentation to understand how to attach and detach listeners
ipcMain.removeListener(channel, listener)
}
render() {
// stuff
}
}
关于javascript - 如何避免在 React 组件中使用事件监听器无限重新渲染?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44057551/