【问题标题】:React child renders before parent在父级之前反应子级渲染
【发布时间】:2018-02-03 11:53:33
【问题描述】:

我正在为 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;

【问题讨论】:

  • 有问题吗?你有问题吗?

标签: javascript reactjs react-lifecycle


【解决方案1】:

您可以通过检查坐标是否已经处于状态来有条件地渲染Fetch:

<div>
  { this.state.lon && this.state.lat && <Fetch lon={this.state.lon} lat={this.state.lat} /> }
</div>

【讨论】:

  • 现在它显示未处理的承诺:数据未定义...你能帮我解决这个问题吗?
  • 请把这一行改成:const {data} = await res.json(); 这个const data = await res.json(); 那里不需要解构。
猜你喜欢
  • 2016-12-06
  • 2017-11-16
  • 2018-12-11
  • 2017-03-06
  • 2021-04-21
  • 1970-01-01
  • 1970-01-01
  • 2021-02-28
  • 2021-02-26
相关资源
最近更新 更多