useCallBack挂钩中的状态变得不确定,我认为它没有获得状态变量的作用域
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 })
}, [])
设置位置Iam获取对象{ “ lat”:37.775030512686214, “ lng”:-122.4273883345241, }
其中在控制台中未定义保存位置
答案 0 :(得分:1)
您需要提供selectedLocation
作为依赖项。否则,状态更改后,回调将不会更新。
const saveLocationPickerHandler = useCallback(() => {
console.log('saveLocation', selectedLocation)
if (!selectedLocation) {
return;
}
props.navigation.navigate('DeliveryLocation', { pickedLocation: selectedLocation })
}, [selectedLocation])
如果提供一个空数组作为依赖项,则useCallback函数将始终具有初始状态,并且从不更新(selectedLocation)。 这与useEffect具有的行为相同