electron 如何从节点js函数更新redux状态

qyuhtwio  于 2022-12-16  发布在  Electron
关注(0)|答案(1)|浏览(223)

我正在创建一个程序,该程序真实的绘制串行端口发送的数据。我使用电子,所以在main.js文件(在那里创建应用程序的窗口)中,我已经声明了接收数据时的事件。

const { SerialPort, ReadlineParser } = require('serialport');

const port = new SerialPort({
  path: 'COM5',
  baudRate: 9600,
});
const parser = new ReadlineParser({ delimiter: '\r\n' });
port.pipe(parser);
let anterior = '';
let cont = 0;
// on data print the complete data from the serial port
parser.on('data', (line) => {
  let value = line.substring(5, 15);

  value = parseFloat(value.trim());

  if (value > 0.0 && !line.includes('?') && line != anterior) {
    console.log(`> ${line}`);
    anterior = line;
    updateStateFromNode(value, cont);
    cont += 1;
  }
});

我调用的函数如下:

import { store } from '../store/store'; // my actual store
import { addValue, addLabel } from '../store/data';

function updateStateFromNode(newValue, newLabel) {
      store.dispatch(addValue(newValue));
      store.dispatch(addLabel(newLabel));
    }

我在函数addValue内部进行控制台日志,以检查它是否到达该函数,并且它确实...
我也尝试了customHook,但它也不工作.
有谁知道我是怎么做到的?

bq9c1y66

bq9c1y661#

main和renderer进程彼此隔离,这意味着从main调度不会更新renderer上的存储。要在两个进程之间通信,可以使用IPC。假设使用预加载文件,可以执行如下操作:

主要

function updateStateFromNode(newValue, newLabel) {
  // We will use a channel named "updateState"
  mainWindow.webContents.send("updateState", newValue, newLabel);
}

字符串

预载

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

contextBridge.exposeInMainWorld("electronAPI", {
  onUpdateState: (callback) => {
    const channel = "updateState";
    const subscription = (_event, ...args) => callback(...args);

    // Sets the listener on the channel "updateState"
    ipcRenderer.on(channel, subscription);

    // Returns a function to remove the listener
    return () => {
      ipcRenderer.removeListener(channel, subscription);
    };
  }
})

渲染器

import { addValue, addLabel } from "../store/data";

const { electronAPI } = window; // `electronAPI` is exposed with the preload

const MyComponent = () => {
  const dispatch = useDispatch();

  useEffect(() => {
    // Calls the function from preload to set the listener on the channel "updateState"
    const removeUpdateStateListener = electronAPI.onUpdateState((newValue, newLabel) => {
      dispatch(addValue(newValue));
      dispatch(addLabel(newLabel));
    });
    
    return removeUpdateStateListener; // Removes the listener on unmount
  }, [dispatch]);

  return (...);
}

相关问题