React Native使用react_native_mqtt连接MQTT报错如何修改app.js代码?
核心报错原因
你遇到的_reactNativeMqtt.default is not a function报错是因为react-native-mqtt的导入方式错误,且你调用了不存在的init方法:该库没有默认导出的init函数,只暴露了Paho对象供使用。
具体修改点
- 修正导入逻辑,删除冗余的init代码
替换掉原来的导入和init调用部分:
// 删掉这部分 import init from 'react-native-mqtt' init({ size: 10000, defaultExpires: 1000 * 3600 * 24, enableCache: true, sync: {}, });
替换为正确的导入:
import { Component } from 'react'; import { View, Text, TextInput, Button, StyleSheet } from 'react-native'; import { Paho } from 'react-native-mqtt';
- 修正MQTT客户端实例化参数
Paho.MQTT.Client的第一个参数是纯host,不需要带mqtt://协议前缀,同时端口要传入数字类型,删掉clientId后多余的逗号:
// 删掉原来的connectUrl定义 const host = '55.122.xx.xx' const port = 1883 // 改成数字类型 const clientId = `mqtt_${Math.random().toString(16).slice(3)}` // 实例化客户端 const client = new Paho.MQTT.Client(host, port, clientId);
- 修复onMessageArrived方法的变量错误
方法里的message变量不存在,替换为传入的参数名entry:
onMessageArrived(entry) { console.log("onMessageArrived:"+entry.payloadString); this.setState({message: [...this.state.message, entry.payloadString]}); }
- 修复sendMessage方法的变量声明问题
message变量没有声明,前面加const关键字:
sendMessage(){ const message = new Paho.MQTT.Message(this.state.messageToSend); // 后续逻辑保持不变 }
- 调整连接逻辑的执行时机
不要在constructor中执行MQTT连接操作,新增componentDidMount生命周期方法,把连接逻辑移进去:
// constructor里只保留客户端实例化、方法绑定、state初始化,删掉connect调用 constructor(){ super(); this.onMessageArrived = this.onMessageArrived.bind(this) this.onConnectionLost = this.onConnectionLost.bind(this) const client = new Paho.MQTT.Client(host, port, clientId); client.onMessageArrived = this.onMessageArrived; client.onConnectionLost = this.onConnectionLost; this.state = { message: [''], client, messageToSend:'', isConnected: false, }; } // 新增生命周期方法 componentDidMount() { this.state.client.connect({ onSuccess: this.onConnect, useSSL: false , userName: 'User', password: 'Pass', onFailure: (e) => {console.log("连接失败" , e); } }); }
额外调试提示
- 确认你填写的MQTT broker地址、端口、用户名密码正确,测试设备和broker网络连通,1883端口没有被防火墙拦截
onConnect方法中现在订阅的是hello/world主题,替换为你实际传感器上报数据的主题即可获取对应数据
内容的提问来源于stack exchange,提问作者Keltouma Indtaher
相关产品推荐
相关产品推荐

