electron ipcMain ipcRenderer通信 dialog选择文件 避坑

2 篇文章 0 订阅
1 篇文章 0 订阅

主进程

import { ipcMain, dialog } from 'electron';
// 忽略其他...
ipcMain.on('open-file-dialog', (event) => {
   dialog
     .showOpenDialog({
       filters: [{ name: '文件类型', extensions: ['xlsx'] }],
     })
     .then((res) => {
       event.sender.send('selected-path', res.filePaths);
     })
     .catch(console.log);
 });

渲染进程

import { ipcRenderer } from 'electron';
import fs from 'fs';
import Excel from 'exceljs';
// 忽略其他逻辑...
const handleSelectFile = () => {
   ipcRenderer.send('open-file-dialog');
	//注册一次监听事件,之后注销此监听事件
   ipcRenderer.once('selected-path', async (_event: any, paths: Array<string>) => {
     if (!paths[0]) return;
     const buffer = fs.readFileSync(paths[0]);
     // 其他操作
   });
};

避坑

在使用ipcRenderer监听时,监听函数可能会出现多次调用的情况:

import { ipcRenderer } from 'electron';
import fs from 'fs';
import Excel from 'exceljs';
// 忽略其他逻辑...
const handleSelectFile = () => {
   ipcRenderer.send('open-file-dialog');
   // 监听和发送放在同一个函数中。
   // 原因可能是组件更新导致函数调用,写在同一函数中可以避免此类问题。
};

// 注册监听事件,不会注销,注册好后会重复多次调用监听函数,once也是一样效果
// 正确做法同上
ipcRenderer.on('selected-path', async (_event: any, paths: Array<string>) => {
  if (!paths[0]) return;
  const buffer = fs.readFileSync(paths[0]);
  // 其他操作
});
  • 1
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值