-1

所以我试图使用 axios 来提取一个 api 以及 HTML5Geolocation。

我将它放在 componentDidMount 中,并希望它至少可以在 console.log 使用异步记录结果并最终将状态设置为国家/地区。

componentDidMount(){
    async onLoad() {
        if (window.navigator.geolocation) {
           window.navigator.geolocation.getCurrentPosition(
           position => {
              const response = axios.get('http://ws.geonames.org/countryCode' , {
                   lat: position.coords.latitude,
                   lng: position.coords.longitude,
                   type: 'JSON'
               });
               console.log('here is the response >>>>', response.countryName); 
               this.setState({ country: response.countryName })
           });

           }
         }

}

但是,这目前不起作用。我正在为我的 API使用Geonames

知道我在代码上做错了什么吗?

4

2 回答 2

1

正如@Shridhar Sharma 所说,删除onLoad。

await的代码中缺少 。没有它的 await 表达式,异步函数的执行将不会等待 Promise 解决。

还要记住一件事,即使浏览器支持地理定位,也可能存在其他错误,例如 PERMISSION_DENIED、POSITION_UNAVAILABLE 和 TIMEOUT。看更多

https://developer.mozilla.org/en-US/docs/Web/API/PositionError/code

componentDidMount() {
        if (window.navigator.geolocation) {
            window.navigator.geolocation.getCurrentPosition( async (position) => {
                const response = await axios.get("http://ws.geonames.org/countryCode", {
                    lat: position.coords.latitude,
                    lng: position.coords.longitude,
                    type: "JSON"
                });
                console.log("here is the response >>>>", response.countryName);
                this.setState({ country: response.countryName });

            }, (e) => {
                // other errors appear here
                console.log(e);
            });
        } else {
            console.log("navigator not supported");
        }
    }
于 2019-05-30T16:12:02.380 回答
0

你在声明onLoad方法但没有调用它,删除声明并直接调用代码,因为在里面声明一个方法没有意义componentDidMount

componentDidMount() {
  if (window.navigator.geolocation) {
    window.navigator.geolocation.getCurrentPosition(
      position => {
        const response = axios.get('http://ws.geonames.org/countryCode', {
          lat: position.coords.latitude,
          lng: position.coords.longitude,
          type: 'JSON'
        });
        console.log('here is the response >>>>', response.countryName);
        this.setState({
          country: response.countryName
        })
      });
  }
}
于 2019-05-30T14:48:49.313 回答