React Native:状态在 useCallBack 挂钩函数内变得未定义

yas*_*eri 4 javascript react-native react-navigation react-hooks

状态在 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 })
}, [])
Run Code Online (Sandbox Code Playgroud)

设置位置我正在获取对象 { "lat": 37.775030512686214, "lng": -122.4273883345241, }

其中 savelocation 在控制台中未定义

Tob*_*ins 10

您需要提供selectedLocation作为依赖项。否则,如果状态发生变化,回调将不会更新。

const saveLocationPickerHandler = useCallback(() => {
    console.log('saveLocation', selectedLocation)
    if (!selectedLocation) {
        return;
    }
    props.navigation.navigate('DeliveryLocation', { pickedLocation: selectedLocation })
}, [selectedLocation])
Run Code Online (Sandbox Code Playgroud)

如果您提供一个空数组作为依赖项,则 useCallback 函数将始终具有初始状态并且永远不会更新(selectedLocation)。这与 useEffect 的行为相同