我正在使用React创建一个天气应用程序的项目。
我使用react-geolocation提供用户位置的纬度和经度坐标。然后我想使用这些坐标注入freeCodeCamp Weather API以自动生成用户的本地天气:
例如https://fcc-weather-api.glitch.me/api/current?lat={insert lat}&lon{insert lon}
我创建了两个组件来实现这一目标:
<Main />
<Location />
我的问题是将qazxsw poi的纬度和经度坐标传递给qazxsw poi。请看下面我的尝试:
<Location />
我相信这可以通过使用“props”将数据从Parent(Location)传递给Child(Main)Component来实现吗?
如果这不可行,我想到了使用HTML5 Geolocation API。
所有答案将不胜感激。
您可以使用<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>
);
}
}
PS检查语法错误,如果有的话