javascript - 在反应中将数据添加到字典中
问题描述
我正在使用 mqtt 接收一些数据,我想将该数据直接添加到字典中。
我将数据添加到字典的可能天真的方法如下:
this.client.on('message', (topic, message) => {
this.state.mqttMessage[topic] = message.toString();
})
我还尝试了以下方法:
this.setState(prevState => ({
mqttMessage: {
...prevState.mqttMessage,
topic: message.toString()
}
}))
但这会将关键字“主题”添加到字典中。
上面的行似乎也产生了以下警告:
Do not mutate state directly. Use setState() react/no-direct-mutation-state
稍后我想使用以下代码显示上面收到的内容:
render() {
console.log(this.props.mqttMessage)
return (
<div>
test1: {this.props.mqttMessage["test1"]} <br/>
test2: {this.props.mqttMessage["test2"]} <br/>
test3: {this.props.mqttMessage["test3"]} <br/>
</div>
);
}
但问题是对象似乎没有直接更新,我需要刷新页面才能启动内容。我想我没有正确使用 setState。做我想做的事情的正确方法将不胜感激。
下面是整个代码:
import React, { Component } from 'react';
import Button from 'react-bootstrap/lib/Button';
import Tab from 'react-bootstrap/lib/Tab';
import Tabs from 'react-bootstrap/lib/Tabs';
import 'rc-slider/assets/index.css';
import './App.css';
class App extends Component {
constructor(props) {
super(props);
this.state = {
mqttMessage: {}
}
this.mqtt = require('mqtt')
this.client = this.mqtt.connect('mqtt://192.168.10.100:9001')
this.client.on('connect', () => {
this.client.subscribe('test1')
this.client.subscribe('test2')
this.client.subscribe('test3')
})
this.client.on('message', (topic, message) => {
this.state.mqttMessage[topic] = message.toString();
})
}
render() {
return (
<div className="App">
<Tabs defaultActiveKey="profile" id="uncontrolled-tab-example">
<Tab eventKey="home" title="Home">
<PostMessage client={this.client} />
</Tab>
<Tab eventKey="seats" title="Seats">
<SeatPage mqttMessage={this.state.mqttMessage} client={this.client} />
</Tab>
</Tabs>
</div>
);
}
}
class PostMessage extends React.Component {
sendMessage = (e) => {
e.preventDefault();
this.props.client.publish('demo/test', 'My Message');
}
render() {
return (
<Button onClick={this.sendMessage}>
Send Message
</Button>
);
}
}
class SeatPage extends React.Component {
sendMessage = (e, topic, message) => {
e.preventDefault();
this.props.client.publish(topic, message);
}
render() {
console.log(this.props.mqttMessage)
return (
<div>
test1: {this.props.mqttMessage["test1"]} <br/>
test2: {this.props.mqttMessage["test2"]} <br/>
test3: {this.props.mqttMessage["test3"]} <br/>
</div>
);
}
}
export default () => (
<App />
);
解决方案
在反应中,您不应该直接更改状态对象。您应该使用 setState 方法。
像下面这样的东西应该可以解决问题。
this.client.on('message', (topic, message) => {
this.setState({
...this.state,
mqttMessage: {
...this.state.mqttMessage,
[topic]: message
}
})
})
推荐阅读
- python - 按列表和总和值过滤行
- php - PHP SoapClient 不适用于我的 WebService。基本身份验证问题?
- postgresql - postgreSQL 到 AWS Aurora PostgreSQL 数据复制
- c# - 不可调用的成员“ListBox.Items”不能像方法一样使用
- r - 如何在 paste() 语句中包含具有多个元素的向量?
- php - Prestashop - 1.7.4.2 - 双 if 语句
- firebase - 如何从 Firebase 存储下载内容并将该内容保存在用户的手机上?
- docker - 使用 docker 服务多个 tensorflow 模型
- android - 更新导入的 Google 库的 APK 扩展文件
- android - 空白代替广告 - ADMOB