最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - React Native : state is getting undefined inside useCallBack hook function - Stack Overflow

programmeradmin4浏览0评论

State is getting undefined inside the useCallBack hook I think it is not getting scope to the state variable

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, }

where as savelocation is undefined in console

State is getting undefined inside the useCallBack hook I think it is not getting scope to the state variable

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, }

where as savelocation is undefined in console

Share Improve this question asked Oct 20, 2019 at 6:04 yaswanthkoneriyaswanthkoneri 4184 silver badges18 bronze badges
Add a ment  | 

1 Answer 1

Reset to default 10

You need to provide selectedLocation as a dependency. Else the callback will not update if the state changes.

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). This is the same behaviour useEffect has

发布评论

评论列表(0)

  1. 暂无评论