javascript - 读取事件监听器未在 native react 中触发

标签 javascript reactjs react-native bluetooth

我正在 native react 中开发一个蓝牙项目,我试图从其他设备读取数据。使用以下代码读取数据

BluetoothSerial.readFromDevice().then((data) => {
      console.log(data)
}

运行完美。 但我想使用事件监听器来收集其他设备在任意时间发送的数据。 我正在使用 https://github.com/rusel1989/react-native-bluetooth-serial/issues/16 中找到的监听器由@andrescheca回答。代码如下所示

    BluetoothSerial.withDelimiter('\r').then(() => {
    Promise.all([
      BluetoothSerial.isEnabled(),
      BluetoothSerial.list()
    ])
    .then((values) => {
      const [ isEnabled, devices ] = values
      this.setState({ isEnabled, devices })
    })

    BluetoothSerial.on('bluetoothEnabled', () => console.log('Bluetooth enabled'))
    BluetoothSerial.on('bluetoothDisabled', () => console.log('Bluetooth disabled'))
    BluetoothSerial.on('read', (data) => {

       console.log(`DATA FROM BLUETOOTH: ${data.data}`);
       Toast.show(data.data);
   })
    BluetoothSerial.on('error', (err) => console.log(`Error: ${err.message}`))
    BluetoothSerial.on('connectionLost', () => {
      if (this.state.device) {
        console.log(`Connection to device ${this.state.device.name} has been lost`)
      }
      this.setState({ connected: false })
    })
  });

当我启用和禁用蓝牙时,所有监听器(即 bluetoothEnabled、bluetoothDisabled)都会触发。但是读取监听器在接收数据时不会触发。我假设它应该在另一个设备发送一些数据时立即触发。 如果有人能帮助我解决这个问题,我将非常感激。

最佳答案

我解决了这个问题,只是在我试图从 Linux 服务器发送到我的设备的数据末尾添加\r 。 感谢@kendavidson 的帮助。

关于javascript - 读取事件监听器未在 native react 中触发,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60365323/

相关文章:

javascript - AngularJS:访问服务中的动态基本 href 值

javascript - 如何管理、加速和预加载页面上的所有图像?

reactjs - React、Typescript、Hooks - 类型上不存在属性 'state'

ios - 使用旧版本的 React Native 的新 React Native 项目

javascript - 如何使用 chrome 扩展程序获取框架的当前 src?

node.js - 用后端请求响应服务器端渲染

javascript - 如何使用 Nextjs 设置 Firebase 托管多站点

ios - 打印 : Entry, ":CFBundleIdentifier", 不存在

javascript - 如何用Realm来组织React Native项目文件?

javascript - jQuery innerHTML 无法正常工作(!)