如何解决如何从网络蓝牙订阅回调更新 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 举报,一经查实,本站将立刻删除。