如何从网络蓝牙订阅回调更新 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>
}

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

相关问答

Selenium Web驱动程序和Java。元素在(x,y)点处不可单击。其...
Python-如何使用点“。” 访问字典成员?
Java 字符串是不可变的。到底是什么意思?
Java中的“ final”关键字如何工作?(我仍然可以修改对象。...
“loop:”在Java代码中。这是什么,为什么要编译?
java.lang.ClassNotFoundException:sun.jdbc.odbc.JdbcOdbc...