如何从node js函数中更新redux状态



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

const { SerialPort, ReadlineParser } = require('serialport');
const port = new SerialPort({
path: 'COM5',
baudRate: 9600,
});
const parser = new ReadlineParser({ delimiter: 'rn' });
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,但它也不起作用。

有人知道我怎么才能做到这一点吗?

主进程和渲染器进程彼此隔离,这意味着从主进程调度不会更新渲染器上的存储。要在两个进程之间进行通信,可以使用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 (...);
}

最新更新