为什么我的活动被调用了这么多次?[反应+电子]

ty1*_*ty1 0 reactjs electron

概括

我正在使用 React 和 Electron 构建一个桌面应用程序。其目的是将文件安装到编码器定义的目录中。文件来自亚马逊S3。我使用 Material UI 框架作为加载栏,并使用 SnackBar 弹出窗口来显示用户成功。要下载,我使用这个库:https://github.com/tytech3/node-s3-client

使用这个库公开了传入的字节值和我们需要的总字节值,因此给了我进度条的百分比。

问题

我正在使用事件(即 ipcMain 和 ipcRenderer)来传递此信息。Main.js(与操作系统一起使用的文件):

 ipcMain.once('downloadDir', (event, arg) => {

  var percentage = 10;

  ipcMain.on('downloaderPercentage', (event, arg) => {
    event.reply('downloadPercentage', percentage);
    percentage += 10;
    console.log("Main % val: " + percentage);
  })

  ipcMain.on('clear', (event, arg) => {
    percentage = 0;
  })

})
Run Code Online (Sandbox Code Playgroud)

和 Test.js (我的反应组件):

  installFiles = (version)  => {
    this.openSnack = false;
    console.log(version);

    this.setState({currentDownload: "Downloading File: " + version, downloading: true})
    ipcRenderer.send('downloadDir', version);
    ipcRenderer.send("downloaderPercentage")

    var that = this;

    ipcRenderer.on('downloadPercentage', (event, arg) => {
          console.log("Testpage %: " + arg);
          that.percentage = arg
          setTimeout(function(){
            if(isMounted && (arg < 100)) {
              ipcRenderer.send("downloaderPercentage")
              that.setState({percentage: arg});
          }
           else{
            console.log("else statement")
            that.resultMessage = 'Installation Successful'
            that.openSnack = true;
            that.setState({currentDownload: '', percentage: 100})
            ipcRenderer.send('clear');
      }}, 500)
      })
    }
Run Code Online (Sandbox Code Playgroud)

我渲染了多个具有安装按钮的卡,它们都使用'installFiles'上面的此功能。第一个按钮效果很好,正如我设计的那样。但是,如果您添加带有另一个按钮的另一张卡,它将多次运行 ipcRenderer 事件,并且它将命中结束 else 语句 12 次。如果再添加一个,数字就会增加。我尝试过删除事件侦听器,但这不起作用。

TLDR 有谁知道为什么我的事件侦听器再次被调用后会被多次点击?

ty1*_*ty1 7

最终弄清楚了。事件监听器从未被删除。添加了 2 行(请参阅以 + 开头的行)以删除侦听器。我相信 ipcRenderer.on 实际上创建了一个新的侦听器,这就是为什么我越来越多。

    ipcRenderer.on('downloadPercentage', (event, arg) => {
      console.log("Testpage %: " + arg);
      that.percentage = arg
      setTimeout(function(){
        if(isMounted && (arg < 100)) {
          ipcRenderer.send("downloaderPercentage")
          that.setState({percentage: arg});
      }
       else{
        console.log("else statement")
        that.resultMessage = 'Installation Successful'
        that.openSnack = true;
        that.setState({currentDownload: '', percentage: 100})
        ipcRenderer.send('clear');
       + ipcRenderer.removeAllListeners('downloadPercentage');
       + ipcRenderer.removeAllListeners('downloaderPercentage');

  }}, 500)
  })
  this.setState({currentDownload: "Installing File: " + version})
}
Run Code Online (Sandbox Code Playgroud)