Reactjs 如何在React应用程序状态下最好地存储MQTT消息的复杂对象?
我想用TypeScript开发一个React应用程序,它可以存储和发送MQTT数据 有很多(数百)条MQTT消息,如:Reactjs 如何在React应用程序状态下最好地存储MQTT消息的复杂对象?,reactjs,typescript,redux,react-redux,mqtt,Reactjs,Typescript,Redux,React Redux,Mqtt,我想用TypeScript开发一个React应用程序,它可以存储和发送MQTT数据 有很多(数百)条MQTT消息,如: config.laser.enable==“true”,config.system.value==“23”或config.user.password==“foobar” 因此,我最终得到了一个对象,如: { "config.laser.enable": true, "config.system.value": 23, &
config.laser.enable==“true”
,config.system.value==“23”
或config.user.password==“foobar”
因此,我最终得到了一个对象,如:
{
"config.laser.enable": true,
"config.system.value": 23,
"config.user.password": "foobar",
...
}
我的每个可视化组件将只使用这些主题的一小部分
我的第一种方法是为每个组件创建一个MQTT客户机,并订阅它们各自的主题,但这似乎是一个很大的开销。所以我认为最好只有一个MQTT客户机,它订阅所有内容并以全局状态存储消息数据。
因此,我的问题是:我如何(或不应该?)在React中以全局状态存储复杂数据(对象),并确保只有组件在其全局状态的特定子集发生更改时才重新绘制。我可以为此使用React-Redux吗
你能给我举个例子说明怎么做吗
我不熟悉React,所以如果这是琐碎的,请原谅。React上下文应该非常适合此类任务。它也是Redux库的主干。 以下是React的摘录: 上下文旨在共享可被视为React组件树的“全局”数据 使用React上下文的概念验证示例:
const GlobalMessages = React.createContext({});
function App() {
return (
<GlobalMessages.Provider value={/* pass the messages here */}>
<SomeComponent/>
<RandomContainer/>
</GlobalMessages.Provider>;
)
}
function SomeComponent() {
// All instances of SomeComponent nested at any level inside
// GlobalMessages.Provider will now have access to its value.
let msgContext = useContext(GlobalMessages);
let message = msgContext.messageTypeA; // Your "selector"
return <Textbox value={message} />;
}
把你想要的东西列成一个白名单,忽略其他的(根本不要把它们设置成状态)?在许多不同的组件中需要太多的对象。我需要一个全球性的国家,太好了。这种全球背景和记忆效果惊人地好。
function SomeComponent() {
let msgContext = useContext(GlobalMessages);
let message = msgContext.messageTypeA; // Your "selector"
return useMemo(() => {
// The rest of your rendering logic
return <ExpensiveComponent value={message} />;
}, [message])
}