简体   繁体   English

React Native:state 在 useCallBack 钩子 function 内变得未定义

[英]React Native : state is getting undefined inside useCallBack hook function

State is getting undefined inside the useCallBack hook I think it is not getting scope to the state variable State 在 useCallBack 钩子中变得未定义我认为它没有将 scope 传递给 state 变量

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 })
}, [])

set location Iam getting Object { "lat": 37.775030512686214, "lng": -122.4273883345241, }设置位置我得到 Object {“lat”:37.775030512686214,“lng”:-122.4273883345241,}

where as savelocation is undefined in console在控制台中未定义保存位置的位置

You need to provide selectedLocation as a dependency.您需要提供selectedLocation作为依赖项。 Else the callback will not update if the state changes.否则,如果 state 更改,回调将不会更新。

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

If you provide an empty array as dependency the useCallback function will always have the initial state and never update (selectedLocation).如果您提供一个空数组作为依赖项,则 useCallback function 将始终具有初始 state 并且永远不会更新(selectedLocation)。 This is the same behaviour useEffect has这与 useEffect 的行为相同

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM