Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
281 views
in Technique[技术] by (71.8m points)

javascript - how to communicate between react and electron

Creating desktop application using react and electron.I want to call method in main.js of electron from react component.In angular there was a npm package.

import React, { useState, useEffect, useRef } from 'react';
import './diagnosis.css';
const electron = window.require('electron');// if i use require('electron') throws error
function Diagnosis(props) {
    const [data, setData] = useState({ hits: [] });
    useEffect(() => {
        getExeFiles();
    });
    const getExeFiles = () => {
        electron.ipcRenderer.send('get-exe'); 
    }
    return(<></>)
}

main.js

electron.ipcMain.on('get-exe', () => {
    console.log('reaciovg');
    mainWindow.webContents.send('return-exe', '');
});

How to overcome this issue?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

At your Renderer.js

const { ipcRenderer } = require('electron');

async function runCommand(cmd) {
  const res = await ipcRenderer.sendSync('runCommand', cmd);
  return res;
}

At you main.js

// Listen event through runCommand channel
// And return the result to Renderer.
ipcMain.on('runCommand', async (event, arg) => {
  event.returnValue = await runCommand(arg);
});

This is the simplest way to communicate between main and renderer process.

But I think you are going to send the result from the main process to renderer using mainWindow.webContents.send('return-exe', '');

So this means, you are sending the result through return-exe IPC channel from main to renderer. And you should listen event from this channel at your renderer. Like this

ipcRenderer.on('retrun-exe', (event, arg) => {
    ...
});

You can add this listener at your lifecycle functions. I was used to add this to componentDidMount() But in your case, please add this to your useEffect()


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...