I recently downloaded paho-mqtt
via yarn. The problem is I am not sure if I am importing it correctly, because I am getting an error:
Cannot read property 'Client' of undefined
The way I am importing and using it is like this:
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);
}
location.host = a string for the IP
location.port = a number for the port
location.clientID = a string for the clientID
If it is relevant, I am attempting to use it within a React Native app.
Maybe this module is not meant to be downloaded via NPM or Yarn? Or maybe I am not supposed to be importing "Paho"?
EDIT: when using react-native-paho-mqtt
--this is the code I am using:
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
}
I notice that whenever I enter anything that isn't prefaced with ws:// (web sockets) I would get a URI error.
The paho-mqtt library has changed, and the example code is incorrect
var client = new Paho.MQTT.Client(location.host, location.port, location.clientID)
Should be changed to (remove MQTT from Object path):
var client = new Paho.Client(location.host, location.port, location.clientID)
See the "breaking changes" in the GitHub README page: paho.mqtt.javascript
试试这个react-native兼容库: https : //www.npmjs.com/package/react-native-paho-mqtt
yarn add react-native-paho-mqtt
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.