我需要进行状态更新并使用它。我尝试了几种方法,如果在发出请求并返回响应后打印dropOffCoordinates
,即使使用.then()
也不会更新状态。我尝试将setDropOffCoordinates()
放在useEffect挂钩中,但无法正常工作。
import React, { useState, useEffect, useContext, useRef } from "react";
const [dropOffCoordinates, setDropOffCoordinates] = useState({
latitude: 0,
longitude: 0
});
const getCoordinatesofDropoffPlace = place_id => {
getPlaceCoordinates(place_id)
.then(response => {
console.log('response drop off: ', response)
setDropOffCoordinates( dropOffCoordinates =>
({
...dropOffCoordinates,
latitude: response.lat,
longitude: response.lng
})
);
console.log("after: ", dropOffCoordinates)
})
.then( () => console.log('dropOffCoordinates', dropOffCoordinates) )
.catch(error => {
console.log(error);
});
};
useEffect(
() => {
getCoordinatesofDropoffPlace
}, [dropOffCoordinates]
)
我在组件内部的可触摸不透明onPress函数中调用此函数
onPress={ () => {
getCoordinatesofDropoffPlace(place.place_id);
}
答案 0 :(得分:1)
调用setState时。 React将准备更新应用程序树,但是变量dropOffCoordinates仍然相同。我将尝试:
getPlaceCoordinates(place_id)
.then(response => {
console.log('response drop off: ', response)
console.log("component coordinates will be the same until reload", dropOffCoordinates)
const coordinates = {
latitude: response.lat,
longitude: response.lng
}
// do your job with coordinates
setDropOffCoordinates(coordinates)
})
.catch(error => {
console.log(error);
});
const [dropOffCoordinates, setDropOffCoordinates] = React.useState({
latitude: 0,
longitude: 0
});
const getCoordinatesofDropoffPlace = place_id => {
getPlaceCoordinates(place_id)
.then(response => {
console.log("response drop off: ", response);
const newCoordinates = {
latitude: response.lat,
longitude: response.lng
}
// you can use newCorrdinates to do your job
setDropOffCoordinates(newCoordinates);
})
.catch(error => {
console.log(error);
});
};
React.useEffect(() => {
// DO HERE YOUR JOB ON UPDATE
}, [dropOffCoordinates]);