我正在使用 mqtt 接收一些数据,我想将该数据直接添加到字典中。
我将数据添加到字典的可能很幼稚的方法如下:
this.client.on('message', (topic, message) => {
this.state.mqttMessage[topic] = message.toString();
})
我还尝试了以下方法:
this.setState(prevState => ({
mqttMessage: {
...prevState.mqttMessage,
topic: message.toString()
}
}))
但这会将关键字“topic”添加到字典中。
上面的行似乎也产生了以下警告:
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 />
);
最佳答案
在 React 中你不应该直接改变状态对象。您应该使用 setState 方法。
像下面这样的东西应该可以解决问题。
this.client.on('message', (topic, message) => {
this.setState({
...this.state,
mqttMessage: {
...this.state.mqttMessage,
[topic]: message
}
})
})
关于javascript - 在 react 中将数据添加到字典,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53739564/