在按钮上单击“设置状态”后,Ionic React Promise不等待

问题描述

好的,我有以下问题:

单击按钮后,我想执行一个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",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地理代码(地址)解析为继续执行该方法

有人可以告诉我我在想什么吗?

解决方法

我通过使用常规Promises(而非异步/等待)解决了该问题。

相关问答

Selenium Web驱动程序和Java。元素在(x,y)点处不可单击。其...
Python-如何使用点“。” 访问字典成员?
Java 字符串是不可变的。到底是什么意思?
Java中的“ final”关键字如何工作?(我仍然可以修改对象。...
“loop:”在Java代码中。这是什么,为什么要编译?
java.lang.ClassNotFoundException:sun.jdbc.odbc.JdbcOdbc...