[英]How to avoid infinite re-rendering with event listener in React Component?
I have a React/ Electron app. 我有一个React / Electron应用程序。 I need to get some database table from my main.js, and I need to set the state to this table. 我需要从main.js中获取一些数据库表,并且需要将状态设置为该表。
For this, i have written the following listener: 为此,我编写了以下侦听器:
ipcRenderer.on('sendTable', (evt, arg) => {
this.props.setTable(arg);
});
It waits for main.js to send a 'sendTable' event, with the table as the argument. 它等待main.js发送“ sendTable”事件,并将表作为参数。 Then, I set my Redux store to that table. 然后,我将Redux存储设置为该表。 This kind of works. 这种作品。
However, I don't know where to put this listener. 但是,我不知道将这个侦听器放在哪里。 If I put it in the constructor or render function of my component, I end up with an infinite loop. 如果将其放在组件的构造函数或渲染函数中,则会导致无限循环。 But I need to set this up once, since I do need to listen. 但是我需要设置一次,因为我确实需要听。 Where could I put it? 我可以放在哪里?
It's a good practice to attach the event listeners in the componentDidMount
and detach the event listeners in the componentWillUnmount
! 它是附加在一个事件侦听一个很好的做法componentDidMount
,并在分离的事件侦听componentWillUnmount
!
See the code example: 请参见代码示例:
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
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.