我正在执行BLE项目并成功连接到设备。在流传输数据时,我从事件中获取了心率数据。但是状态没有传递给useCallback函数,并定义为空数组。
代码
const samples = 200
const sampleData = _.fill(Array(samples), 0)
const [heartRateValues, setHeartRateValues] = useState(sampleData)
const [heartRateMeasurementListener, setHeartRateMeasurementListener] = useState(null)
useEventListener(
'characteristicvaluechanged',
handleHeartRateMeasure,
heartRateMeasurementListener
);
const handleHeartRateMeasure = useCallback(async(event) => {
console.log(heartRateValues) // <----- [] empty
},[heartRateValues])
const connectBLE = async() => {
let res = await bleConnect()
// ble device successfully connected.
if(res){
startNotificationsHeartRateMeasurement().then((heartRateMeasurementListener) => {
setHeartRateMeasurementListener(heartRateMeasurementListener)
})
}
});
BLE
export const startNotificationsHeartRateMeasurement = () => {
return _startNotifications('heart_rate_measurement');
}
function _startNotifications(characteristicUuid) {
let characteristic = _characteristics.get(characteristicUuid);
return characteristic.startNotifications()
.then(() => characteristic);
}
UseEventListener
export const useEventListener = (eventName, handler, element = window) => {
// Create a ref that stores handler
const savedHandler = useRef();
// Update ref.current value if handler changes.
// This allows our effect below to always get latest handler ...
// ... without us needing to pass it in effect deps array ...
// ... and potentially cause effect to re-run every render.
useEffect(() => {
savedHandler.current = handler;
}, [handler]);
useEffect(
() => {
// Make sure element supports addEventListener
// On
const isSupported = element && element.addEventListener;
if (!isSupported) return;
// Create event listener that calls handler function stored in ref
const eventListener = event => savedHandler.current(event);
// Add event listener
element.addEventListener(eventName, eventListener);
// Remove event listener on cleanup
return () => {
element.removeEventListener(eventName, eventListener);
};
},
[eventName, element] // Re-run if eventName or element changes
);
};
问题
heartRateValues为空[],而不是值数组。