[英]React child renders before parent
我正在為freecodecamp制作WeatherApp。 我已經創建了一個用於獲取地理位置的父類,然后將坐標值傳遞給Fetch.js,問題是當我運行程序時,控制台顯示Fetch可能首先被執行,
即,在控制台上,首先數據顯示Fetch.js的空對象,然后控制台顯示我在Geolocation.js中打印的地理位置
父類:Geolocation.js
import React from 'react';
import Fetch from './Fetch';
class GeoLocation extends React.Component {
constructor(props) {
super(props);
this.state={
lon : null,
lat : null
};
this.showPosition = this.showPosition.bind(this);
}
componentDidMount(){
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(this.showPosition);
} else {
console.log("Geolocation is not supported by this browser.");
}
}
showPosition(position) {
this.setState({lon:position.coords.latitude,lat:position.coords.longitude})
console.log(this.state);
}
render(){
return (
<div>
<Fetch lon={this.state.lon} lat={this.state.lat} />
</div>
)
}
}
export default GeoLocation;
Fetch.js:
import React from 'react';
import LocalWeather from './LocalWeather';
import Icon from './Icon';
class Fetch extends React.Component{
constructor(props){
super(props);
this.state = {};
this.selectHandler = this.selectHandler.bind(this);
this.setStateAsync = this.setStateAsync.bind(this);
}
setStateAsync(){
return new Promise((resolve)=>{
this.setState(this.state,resolve)
})
}
async componentDidMount(){
console.log(this.props.lat);
if(this.props.lat && this.props.lon){
const res = await fetch(`https://fcc-weather-api.glitch.me/api/current?lat=${this.props.lat}&lon=${this.props.lon}`);
const {data} = await res.json();
const temp = data.main['temp'] ;
const icon = data.weather[0].icon ;
await this.setStateAsync({temp:temp,icon:icon});
console.log(data);
}
else {
this.setStateAsync({temp:'',icon:''});
console.log('nothing');
}
}
selectHandler(temp){
this.setState({temp:temp})
}
render(){
return(
<div>
<LocalWeather temp={this.state.temp} on_click={this.selectHandler} />
<Icon src={this.state.icon ? this.state.icon : ''} />
</div>
)
}
}
export default Fetch;
您可以通過檢查坐標是否已處於狀態來有條件地渲染Fetch
:
<div>
{ this.state.lon && this.state.lat && <Fetch lon={this.state.lon} lat={this.state.lat} /> }
</div>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.