You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Electron应用中SQLite数据无法传递至React UI的问题排查

问题解决:Electron中SQLite查询数据无法传递到React UI

问题根源

你的ipcMain.handle('get-notes')函数里,sqlite3的dbs.all()是回调风格API,并非Promise,所以await不会等待查询完成,整个handle函数没有返回实际的查询结果——虽然你在回调里能打印数据,但这个返回值不会被handle函数捕获,最终导致渲染进程调用invoke时拿到undefined。

修复方案

把dbs.all()包装成Promise,让async/await能正确等待查询完成并返回数据:

修改main.ts中的get-notes处理逻辑:

ipcMain.handle('get-notes', async () => {
    const dbs = await db();
    const sql = "SELECT note FROM notes";
    try {
        // 将回调风格的all方法包装为Promise
        const notesDatas = await new Promise((resolve, reject) => {
            dbs.all(sql, (err, data) => {
                if (err) reject(err);
                else resolve(data);
            });
        });
        console.log(notesDatas);
        return notesDatas; // 正确返回数据给渲染进程
    } catch (error) {
        console.log(error);
        return [];
    }
});

额外检查点

确保你的preload脚本正确暴露了Electron的IPC invoke方法,示例如下:

// preload.ts
import { contextBridge, ipcRenderer } from 'electron';

contextBridge.exposeInMainWorld('electron', {
    invoke: (channel: string, ...args: any[]) => ipcRenderer.invoke(channel, ...args),
    send: (channel: string, ...args: any[]) => ipcRenderer.send(channel, ...args)
});

修改后,渲染进程的fetchNotes函数就能正确拿到查询数据并更新UI。

内容的提问来源于stack exchange,提问作者Wesley Pigny

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.14 16:10:02