Ionic React Promise 在按钮点击设置状态后不等待

Ionic React Promise not waiting after setting State on button click

好的,我有以下问题:

单击按钮时,我想执行 GET 请求以检索地址的 lat/lon 数据,更新组件的状态,然后使用更新后的状态转到下一页数据.

我的代码如下所示:

// 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 geocode(address) 解决后继续执行方法。

谁能告诉我我错过了什么?

我使用常规 Promises 解决了这个问题,而不是 async/await。