状态在useCallBack hook中变得未定义,我认为它没有获得状态变量的范围
const [selectedLocation, setSelectedLocation] = useState()
const selectLocationHandler = (event) => {
setSelectedLocation({
lat: event.nativeEvent.coordinate.latitude,
lng: event.nativeEvent.coordinate.longitude
})
console.log('set location', selectedLocation)
}
const saveLocationPickerHandler = useCallback(() => {
console.log('saveLocation', selectedLocation)
if (!selectedLocation) {
return;
}
props.navigation.navigate('DeliveryLocation', { pickedLocation: selectedLocation })
}, [])
设置位置我正在获取对象 { "纬度": 37.775030512686214, "LNG": -122.4273883345241, }
其中 as 保存位置在控制台中未定义
您需要提供selectedLocation
作为依赖项。否则,如果状态更改,回调将不会更新。
const saveLocationPickerHandler = useCallback(() => {
console.log('saveLocation', selectedLocation)
if (!selectedLocation) {
return;
}
props.navigation.navigate('DeliveryLocation', { pickedLocation: selectedLocation })
}, [selectedLocation])
如果提供一个空数组作为依赖项,则 useCallback 函数将始终具有初始状态,并且永远不会更新(selectedLocation(。 这与使用效果具有相同的行为