Javascript 渲染过程中渲染器出现电子错误
我正在学习Electron和更多节点,但每次与IPC渲染器交互时都会出错Javascript 渲染过程中渲染器出现电子错误,javascript,node.js,electron,Javascript,Node.js,Electron,我正在学习Electron和更多节点,但每次与IPC渲染器交互时都会出错 render.js:6 Uncaught ReferenceError: Cannot access 'ipc' before initialization at updateRP (render.js:6) at HTMLButtonElement.onclick (index.html:11) 就我从各种论坛上所知,当我将节点交互添加到我的主要流程中时,这个问题应该已经解决了。我真的很困惑,如果能帮上忙,我将不胜感激
render.js:6 Uncaught ReferenceError: Cannot access 'ipc' before initialization
at updateRP (render.js:6)
at HTMLButtonElement.onclick (index.html:11)
就我从各种论坛上所知,当我将节点交互添加到我的主要流程中时,这个问题应该已经解决了。我真的很困惑,如果能帮上忙,我将不胜感激
代码:
HTML
你好,世界!
在提供的代码中,处理require('electron')
返回的对象的方式非常奇怪,至少可以说
在渲染器中:
const electron = require('electron');
const ipc = electron.ipcRenderer;
const { app, BrowserWindow, ipcMain } = require('electron');
const ipc = ipcMain;
应该是:
const { ipcRenderer } = require('electron');
const ipc = ipcRenderer;
或:
或:
同样,在main中:
const electron = require('electron');
const ipc = electron.ipcRenderer;
const { app, BrowserWindow, ipcMain } = require('electron');
const ipc = ipcMain;
可以在没有任何冗余的情况下重写,如下所示:
const { app, BrowserWindow, ipcMain: ipc } = require('electron');
或者更简洁地说:
const createWindow = () => {
// Create the browser window.
const mainWindow = new BrowserWindow({
width: 800,
height: 600,
webPreferences: {
nodeIntegration: true
}
});
// and load the index.html of the app.
mainWindow.loadFile(path.join(__dirname, 'index.html'));
// Open the DevTools.
};
[更新]
我刚刚注意到主进程代码中的另一个潜在问题:变量mainWindow
必须是全局变量,这样它的值就不会被垃圾收集。。。
看这个
而不是:
let mainWindow;
const createWindow = () => {
// Create the browser window.
mainWindow = new BrowserWindow({
width: 800,
height: 600,
webPreferences: {
nodeIntegration: true
}
});
// and load the index.html of the app.
mainWindow.loadFile(path.join(__dirname, 'index.html'));
// Open the DevTools.
};
使用:
let mainWindow;
const createWindow = () => {
// Create the browser window.
mainWindow = new BrowserWindow({
width: 800,
height: 600,
webPreferences: {
nodeIntegration: true
}
});
// and load the index.html of the app.
mainWindow.loadFile(path.join(__dirname, 'index.html'));
// Open the DevTools.
};