javascript - 如何避免在 React 组件中使用事件监听器无限重新渲染?

标签 javascript reactjs events electron addeventlistener

我有一个 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/

相关文章:

javascript - React Rails 组件 : manually triggering a re-render

带有 iframe 的 Javascript 显示/隐藏 div 适用于除 IE 之外的所有内容

javascript - 我如何使用 react 路由器传递重定向参数?

javascript - 为什么 localStorage 中的更改直到刷新才更新?

python - SQLAlchemy 事件接口(interface)

c# - 编写事件访问器时的多线程问题

javascript - 使用jquery从父元素中删除div子元素

reactjs - 如果 this.node 是 react 组件的引用,则 this.node.contains 不起作用

c# - 将接口(interface)的事件从 VB.Net 转换为 C#

javascript - 使用 clearInterval() 时出错