Я пытаюсь создать небольшой погодный виджет, где геолокация пользователя фиксируется в одном компоненте, а затем передается дочернему компоненту, который извлекает данные о погоде (в зависимости от местоположения), а затем в конечном итоге отображает значок, указывающий текущую погоду. условия.
Я передаю состояние долготы и широты в качестве свойств своего WeatherWidget. К сожалению, WeatherWidget также получает нулевое начальное состояние. Как мне этого избежать?
Спасибо за помощь!
class GetGeolocation extends Component{
constructor(){
super();
this.state = {
lngt: null,
latd: null
}
}
componentDidMount(){
this.getLocation()
}
getLocation = () => {
if(navigator.geolocation){
navigator.geolocation.getCurrentPosition(position => {
this.setState({lngt: position.coords.longitude.toFixed(4)});
this.setState({latd:position.coords.latitude.toFixed(4)});
}
);
};
}
render(){
return (
<>
<WeatherWidget lngt = {this.state.lngt} latd = {this.state.latd} />
</>
)
}
class WeatherWidget extends Component{
constructor(props){
super(props);
this.state = {
weather:[]
}
}
componentWillReceiveProps(nextProps){
this.getWeather(nextProps)
}
getWeather = (location) => {
console.log(location)
// The console logs twice:
// First:
//{lngt: "-12.3456", latd: null}
//Then, the correct values:
//{lngt: "-12.3456", latd: "78,9999"}
}