请检查代码。我想从onMessageArrive检索payloadString数据到构造函数。怎么做?基本上,我想将所有 JSON 数据存储在 Asyncstorage 中,并且还想在构造函数中应用一些逻辑。这就是为什么我想从onMessageArrive检索数据到构造函数。提前谢谢。
import React, { Component } from 'react';
import init from 'react_native_mqtt';
import { AsyncStorage, StyleSheet, Text, View } from 'react-native';
init({
size: 10000,
storageBackend: AsyncStorage,
defaultExpires: 1000 * 3600 * 24,
enableCache: true,
sync: {},
});
export default class MqttLog extends Component {
constructor(props) {
super(props);
const client = new Paho.MQTT.Client('iot.eclipse.org', 443, 'uname');
client.onConnectionLost = this.onConnectionLost;
client.onMessageArrived = this.onMessageArrived;
client.connect({ onSuccess: this.onConnect, useSSL: true });
this.state = {
text: ['ELOGIC'],
client,
};
this.onMessageArrived.bind(this);
}
onConnect = () => {
const { client } = this.state;
client.subscribe('WORLD');
console.log('connect');
};
onConnectionLost = responseObject => {
if (responseObject.errorCode !== 0) {
var connectionLostMessage = `connection lost: ${responseObject.errorMessage}`;
console.log(connectionLostMessage);
}
};
onMessageArrived = message => {
var msg = message.payloadString;
var messageResult = `${msg}`;
console.log(messageResult);
};
render() {
return (
<View style={styles.container}>
<Text>Hello</Text>
</View>
);
}
}
const styles = StyleSheet.create({
container: {
width: '100%',
height: '100%',
},
});
能够通过使用异步存储来解决此问题。当数据来自 mqtt 时,我会立即在异步存储中推送数据,然后使用构造函数中的键值对从异步存储中检索。