【发布时间】:2019-02-08 09:46:43
【问题描述】:
我正在使用 React 创建一个天气应用程序的项目。
我使用react-geolocation 提供用户位置的经纬度坐标。然后我想用这些坐标注入freeCodeCamp Weather API来自动生成用户当地的天气:
例如https://fcc-weather-api.glitch.me/api/current?lat={insert lat}&lon{insert lon}
我创建了两个组件来实现这一点:
<Main /><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>
);
}
}
我相信这可能通过使用“道具”将数据从父(位置)传递到子(主)组件?
如果这不可行,我考虑使用 HTML5 Geolocation API。
所有答案将不胜感激。
【问题讨论】:
-
不要将 react-geolocation 用作应用程序的额外包,您可以使用 html5 地理位置。
-
我确实考虑过使用 HTML5 地理位置。如果是这样,我会在 componentDidMount() 方法中调用这样的代码吗?我可以通过 props 将坐标插入到 freeCodeCamp API 中吗?
-
当然可以
标签: javascript reactjs