how to communicate between react and electron

你说的曾经没有我的故事 提交于 2020-01-24 00:31:53

问题


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?


回答1:


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()



来源:https://stackoverflow.com/questions/59681069/how-to-communicate-between-react-and-electron

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!