基于来自 MQTT 的订阅编写文本

Writing text based on subscription from MQTT

所以我有一个应用程序可以接收来自 Raspberry Pi 的消息。一切都很好,但我不知道如何根据订阅的主题实际输出文本。现在,每当状态发生变化时,我都会将所有主题一个接一个地打印出来。每当关于该特定主题的新状态出现时,文本也不会消失,它们只是有点笨拙地融入一个大字符串。任何帮助将不胜感激。
这是带有订阅的客户端部分:

  constructor(){
    super();
    this.onMessageArrived = this.onMessageArrived.bind(this)
    this.onConnectionLost = this.onConnectionLost.bind(this)


    const client = new Paho.MQTT.Client('broker.hivemq.com', 8000, 'pi@njolac');
    client.onMessageArrived = this.onMessageArrived;
    client.onConnectionLost = this.onConnectionLost;
    client.connect({ 
      onSuccess: this.onConnect,
      useSSL: false ,
      onFailure: (e) => {console.log("here is the error" , e); }

    });

    this.state = {
      message: [''],
      client,
      messageToSend:'',
      isConnected: false,
    };

  }


  onMessageArrived(entry) {
    console.log("onMessageArrived:"+entry.payloadString);
    this.setState({message: [...this.state.message, entry.payloadString]});

  }


  onConnect = () => {
    const { client } = this.state;
    console.log("Connected!!!!");
    client.subscribe('Temperatura');
    client.subscribe('Vlaga');
    client.subscribe('Motor')
    this.setState({isConnected: true, error: ''})
  };

这是文本输出:

<Text style={styles.instructions}>
   Message: {this.state.message}
</Text>

任何帮助都意义重大。提前致谢!

我不太确定该主题在该客户端的 entry 对象中的存储位置。我建议你 console.log(entry) 并查看打印的对象以确定主题的存储位置;它可能是 entry.destinationNameentry.topic.

您的消息正在串联,因为您正在存储消息数组,并将每条新消息附加到此。然后在输出中将整个数组写入屏幕。要么只存储最新消息,要么只显示数组的最后一个元素。

下面的代码是为了说明,还没有debugged/tested:

如果您想显示每个主题的最新消息,您最好将消息存储在字典中:

messageByTopic = {
    'Temperatura': 'temperaturaMessage',
    'Vlaga': 'vlagaMessage'
}

然后在您的输出中,为每个主题(字典中的关键字)写下最新消息:

<div>
{Object.keys(this.state.messageByTopic).map((topic) => {
    return (
      <h4>Topic: </h4> {topic}
      <Text style={styles.instructions}>
          Message: {this.state.messageByTopic[topic]}
      </Text>)
})
</div>

编辑

onMessageArrived(entry) {

    this.setState((state) => ({
        ...state.items,
        messageByTopic: {
            ...state.messageByTopic,
            `${entry.destinationName}`: entry.payloadString
         }
     }));

}