如何从网络蓝牙订阅回调更新 React/Recoil 状态数组?

如何解决如何从网络蓝牙订阅回调更新 React/Recoil 状态数组?

我是使用 React 和 Recoil 的新手,想根据使用 Web Bluetooth API 实时收集的数据显示实时图表(使用 D3)。

简而言之,在调用 await myCharacteristic.startNotifications()myCharacteristic.addEventListener('characteristicvaluechanged',handleNotifications) 后,每次从蓝牙设备通知新值时都会调用 handleNotifications 回调(请参阅 this example)。

我正在使用钩子并尝试从回调中修改后坐力状态(这被简化到极致,我希望它具有代表性):

export const temperatureState = atom({
  key: 'temperature',default: 0
})

export function BluetoothControls() {
  const setTemperature = useSetRecoilState(temperatureState);

  const notify = async () => {
    ...
    temperatureCharacteristic.addEventListener('characteristicvaluechanged',event => {
      setTemperature(event.target.value.getInt16(0))
    }
  }
  return <button onClick={nofity}/>Start notifications</button>
}

如果我想在应用程序的某处显示最新值,这很好用。但是,我有兴趣将最后几个(假设是 10 个)值保留在循环缓冲区中以绘制 D3 图表。

我尝试了以下内容

export const temperatureListState = atom({
  key: 'temperature-list',default: []
})

export function BluetoothControls() {
  const [temperatureList,setTemperatureList] = useRecoilState(temperatureListState);

  const notify = async () => {
    ...
    temperatureCharacteristic.addEventListener('characteristicvaluechanged',event => {
      let temperatureListcopy = temperatureList.map(x => x);
      temperatureListcopy.push(event.target.value.getInt16(0))
      if (temperatureListcopy.length > 10)
        temperatureListcopy.shift()
      setTemperatureList(temperatureListcopy)
    }
  }
  return <button onClick={nofity}/>Start notifications</button>
}

但是,很明显我遇到了问题 described here,其中函数使用的是在渲染期间捕获的旧版本 temperatureList。因此,temperatureState 始终为空,然后替换为包含一个元素的列表。

如何在从外部回调更新的 React state/Recoil atom 中维护一致的列表?我认为 this issue 有点相似,但我想避免使用 Recoil Nexus 等其他扩展程序。

解决方法

useSetRecoilState 接受更新程序函数作为参数,将要更新的值作为第一个参数:

export function BluetoothControls() {
  const setTemperatureList = useSetRecoilState(temperatureListState);

  const notify = async () => {
    ...
    temperatureCharacteristic.addEventListener('characteristicvaluechanged',event => {
      setTemperatureList(t => {
        let temperatureListCopy = t.map(x => x);
        temperatureListCopy.push(event.target.value.getInt16(0))
        if (temperatureListCopy.length > 10)
          temperatureListCopy.shift()
        return temperatureListCopy
      })
    }
  }
  return <button onClick={nofity}/>Start notifications</button>
}

这解决了这个问题,因为更新器函数只对事件进行评估。

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐


Selenium Web驱动程序和Java。元素在(x,y)点处不可单击。其他元素将获得点击?
Python-如何使用点“。” 访问字典成员?
Java 字符串是不可变的。到底是什么意思?
Java中的“ final”关键字如何工作?(我仍然可以修改对象。)
“loop:”在Java代码中。这是什么,为什么要编译?
java.lang.ClassNotFoundException:sun.jdbc.odbc.JdbcOdbcDriver发生异常。为什么?
这是用Java进行XML解析的最佳库。
Java的PriorityQueue的内置迭代器不会以任何特定顺序遍历数据结构。为什么?
如何在Java中聆听按键时移动图像。
Java“Program to an interface”。这是什么意思?
Java在半透明框架/面板/组件上重新绘画。
Java“ Class.forName()”和“ Class.forName()。newInstance()”之间有什么区别?
在此环境中不提供编译器。也许是在JRE而不是JDK上运行?
Java用相同的方法在一个类中实现两个接口。哪种接口方法被覆盖?
Java 什么是Runtime.getRuntime()。totalMemory()和freeMemory()?
java.library.path中的java.lang.UnsatisfiedLinkError否*****。dll
JavaFX“位置是必需的。” 即使在同一包装中
Java 导入两个具有相同名称的类。怎么处理?
Java 是否应该在HttpServletResponse.getOutputStream()/。getWriter()上调用.close()?
Java RegEx元字符(。)和普通点?