use*_*490 5 javascript mqtt paho react-native
我最近paho-mqtt通过yarn下载了。问题是我不确定我是否正确导入它,因为我收到错误:
无法读取未定义的属性“Client”
我导入和使用它的方式是这样的:
import Paho from 'paho-mqtt';
var client = new Paho.MQTT.Client(location.host, location.port, location.clientID)
const MQTTConnectAndMessage = (message) => {
client.connect({onSuccess: sendMQTTMessage})
}
const sendMQTTMessage = (msg) => {
let message = new Paho.MQTT.Message(msg);
message.destinationName = location.messageDestination;
client.send(message);
}
Run Code Online (Sandbox Code Playgroud)
location.host = IP 字符串
location.port = 端口号
location.clientID = clientID 的字符串
如果相关,我将尝试在 React Native 应用程序中使用它。
也许这个模块不适合通过 NPM 或 Yarn 下载?或者也许我不应该导入“Paho”?
编辑:使用时react-native-paho-mqtt--这是我正在使用的代码:
const client = new Client({ uri: 'ws://myiphere/ws', port: 1883, clientId: 'clientId', storage: myStorage});
const sendMQTTMessage = (msg) => {
client.on('connectionLost', (responseObject) => {
if (responseObject.errorCode !== 0) {
console.log("connection lost!");
}
});
client.on('messageReceived', (message) => {
console.log(message.payloadString);
});
client.connect()
.then(() => {
const message = new Message(msg);
message.destinationName = 'F2/BOX2/LED3';
client.send(message);
})
.catch((responseObject) => {
if (responseObject.errorCode !== 0) {
console.log('onConnectionLost:' + responseObject.errorMessage);
}
});
}
export {
sendMQTTMessage
}
Run Code Online (Sandbox Code Playgroud)
我注意到,每当我输入任何不以 ws://(网络套接字)开头的内容时,我都会收到 URI 错误。
paho-mqtt库已更改,示例代码不正确
var client = new Paho.MQTT.Client(location.host, location.port, location.clientID)
Run Code Online (Sandbox Code Playgroud)
应更改为(从对象路径中删除 MQTT):
var client = new Paho.Client(location.host, location.port, location.clientID)
Run Code Online (Sandbox Code Playgroud)
请参阅 GitHub 自述文件页面中的“重大更改”: paho.mqtt.javascript
尝试这个react-native兼容库:https://www.npmjs.com/package/react-native-paho-mqtt
yarn add react-native-paho-mqtt
| 归档时间: |
|
| 查看次数: |
3735 次 |
| 最近记录: |