好的,我有以下问题:
单击按钮后,我想执行一个GET-Request来获取地址的经/纬度数据,更新组件的状态,然后以更新后的状态作为传递数据继续到下一页。
我的代码如下:
// useState setup
const [lat, setLat] = useState(0);
const [lon, setLon] = useState(0);
// async function which sets the state
async function geocode (text: string) {
let request = 'https://geocoder.ls.hereapi.com/6.2/geocode.json?' +
'&searchtext=' + text +
'&maxresults=1'+
'&gen=9'+
'&apiKey=xxx';
fetch(request)
.then(res => res.json())
.then((result) => {
console.log("before setting state values:", result.Response.View[0].Result[0].Location.NavigationPosition[0].Latitude, result.Response.View[0].Result[0].Location.NavigationPosition[0].Longitude);
setLat(result.Response.View[0].Result[0].Location.NavigationPosition[0].Latitude);
setLon(result.Response.View[0].Result[0].Location.NavigationPosition[0].Longitude);
return new Promise<void>((resolve) => {
console.log("in promise values:", lat,lon);
setTimeout(resolve, 10);
})
})
}
// btn click function
async function btnClick (e: any) {
e.preventDefault();
if (checkInputs()) {
await geocode(address);
console.log("after promise values",lat,lon);
history.push({
pathname: '/page/ResultMap',
state: {
address: address,
transportTime: transportTime,
transportType: transportType,
lat: lat,
lon: lon
}
}
)}
}
控制台将我记录下来:
after promise values 0 0
before setting state values: 52.51605 13.37691
in promise values: 0 0
老实说,我希望history.push()一直等到await地理代码(地址)解析为继续执行该方法。
有人可以告诉我我在想什么吗?
答案 0 :(得分:0)
我通过使用常规Promises(而非异步/等待)解决了该问题。