简体   繁体   English

如何从我的嵌套 function 中获取地理定位 API 坐标并进入 React state?

[英]How do I get Geolocation API co-ordinates out of my nested function and into React state?

I'm trying to get a user's location using the Geolocation API when a user clicks a button:当用户单击按钮时,我正在尝试使用Geolocation API获取用户的位置:

<button onClick={this.setNewLatLong()}>"Use my location"</button>;

I can access the lat/long coordinates with the following code:我可以使用以下代码访问纬度/经度坐标:

setNewLatLong = () => { 
 navigator.geolocation.getCurrentPosition(displayLocationInfo);

  function displayLocationInfo(position) {
      const longitude = position.coords.longitude;
      const latitude = position.coords.latitude;

      console.log(`long: ${longitude} | lat: ${latitude}`);
  }
}

But I can't get the data into my state because the latitude and longitude variables are too nested within functions.但是我无法将数据输入到我的 state 中,因为latitudelongitude变量在函数中嵌套得太多了。

How can I get this data into my state?如何将这些数据输入到我的 state 中?

In React, you hold on the information in the component's state.在 React 中,您保留组件的 state 中的信息。 You can set the state like so:您可以像这样设置 state:

this.setState({
  lon: longitude,
  lat: latitude
})

And access the state from your view (render function), or any where else you may need it.并从您的视图(渲染功能)或您可能需要的任何其他地方访问 state。

Every component state update in React should be done with setState() . React 中的每个组件 state 更新都应该使用setState()来完成。 For your case, you can use setState() in the callback function passed into getCurrentPosition() .对于您的情况,您可以在传递给getCurrentPosition()的回调 function 中使用setState() ) 。

navigator.geolocation.getCurrentPosition(position => {
    this.setState({
        lat: position.coords.latitude,
        lng: position.coords.longitude
    });
})

I would also recommend looking into using React hooks for state (after you have finished learning the basics of React)我还建议考虑对 state 使用React 钩子(在您学习完 React 的基础知识之后)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM