地理位置:如何在组件之间传递坐标?



我正在做一个使用 React 创建天气应用程序的项目。

我正在使用反应地理定位来提供用户位置的纬度和经度坐标。然后,我想使用这些坐标注入到 freeCodeCamp 天气 API 中,以自动生成用户的本地天气:

例如https://fcc-weather-api.glitch.me/api/current?lat={insert lat}&lon{insert lon}

我创建了两个组件来实现这一点:

  1. <Main />
  2. <Location />

我的问题是将纬度和经度坐标从<Location />传递到<Main />。请在下面查看我的尝试:

class Location extends Component {
render() {
return(
<div>
<Geolocation
render={({
fetchingPosition,
position: { coords: { latitude, longitude } = {} } = {},
error,
getCurrentPosition
}) =>
<div>
{error &&
<div>
{error.message}
</div>}
{ latitude && longitude && <Main latitude={latitude} longitude={longitude} />}
</div>}
/>
</div>
)
}
}

class Main extends Component {
constructor(props) {
super(props)
this.state = {
lat: null,
lon: null
}
} 
componentDidMount() {
axios.get(`https://fcc-weather-api.glitch.me/api/current?lat={this.props.latitude}&lon={this.props.longitude}`)
.then(res => {
console.log(res.data);
// set state with response data e.g. this.setState()
})
} 
render() {
return (
<div>
// Weather Data 
</div>
);
}
}

我相信这可以通过使用"props"将数据从父(位置(传递到子(主(组件来实现?

如果这是不可能的,我想使用HTML5 Geolocation API。

所有答案将不胜感激。

您可以使用**Html5 Geolocation API**获取当前位置,并且需要向应用添加额外的包以增加应用大小。

下面是示例:

class Main extends Component {
constructor(props) {
super(props)
this.state = {
lat: null,
lon: null
}
} 
componentDidMount() {
if (navigator.geolocation)
navigator.geolocation.getCurrentPosition(this.showPosition, this.showError, options);
}
showPosition = (position) => {
axios.get(`https://fcc-weather-api.glitch.me/api/current?lat={position.coords.latitude}&lon={position.coords.longitude}`)
.then(res => {
console.log(res.data);
// set state with response data e.g. this.setState()
})
}
}
});
}
showError = (error) => {
console.warn("Error", error);
}
render() {
return (
<div>
// Weather Data 
</div>
);
}
}

PS检查语法错误,如果有的话

最新更新