在父组件中进行异步调用之后,使用prop进行反应,更新子组件中的状态

rch*_*hap 4 javascript state async-await reactjs

我正在构建一个天气应用程序,我正在寻找一些最佳实践建议,这些建议是在父组件进行异步调用之后,根据从父组件发送的道具来更新子组件中的状态。

我有一个父组件,该父组件在componentDidMount()方法中对进行异步/等待调用,navigator.geolocation并返回纬度和经度,这些纬度和经度要作为道具发送给子组件。然后,在子组件中,我需要使用道具的经纬度和经度对OpenWeatherMap API进行异步/等待调用。然后,我需要setState()使用response。我不能componentDidMount()在子级中使用它,因为它会在父级异步/等待调用返回之前挂载。

问题是应用程序流程:父组件安装和渲染,并以形式将道具发送给子组件null。子组件将通过nullprops进行安装和渲染。然后,异步/ AWAIT返回在父集的响应lat,并long从响应于状态下componentDidMount(),父母重新呈现,并用正确的值作为发送道具子latlong。子组件会更新道具中的正确值。现在,在这一点上我需要setState()使用这些道具,但是如果componentDidUpdate()不重新渲染为无限循环,我显然无法做到。

那么,什么是完成此任务的好方法?

父组件:

class Container extends React.Component {
  state = {
    cityState: {
      city: "",
      state: ""
    },
    latLong: {
      lat: null,
      long: null
    }
  };

  componentDidMount() {
    this.getCityAndState();
  }

  getCityAndState() {
    let latlng = "";
    if (navigator.geolocation) {
      navigator.geolocation.getCurrentPosition(async position => {
        latlng = `${position.coords.latitude},${position.coords.longitude}`;

        const response = await googleGeolocation.get(
          `json?latlng=${latlng}&location_type=APPROXIMATE&result_type=locality&key=${APIkey}`
        );

        this.setState({
          cityState: {
            city: response.data.results[0].address_components[0].long_name,
            state: response.data.results[0].address_components[2].short_name
          },
          latLong: {
            lat: position.coords.latitude,
            long: position.coords.longitude
          }
        });
      });
    }
  }

  render() {
    return (
      <div className="container">
        <LocationTime location={this.state.cityState} />
        <Forecast location={this.state.latLong} />
      </div>
    );
  }
}
Run Code Online (Sandbox Code Playgroud)

儿童组件:

class Forecast extends React.Component {
  state = {
    today: {},
    secondDay: {},
    thirdDay: {},
    fourthDay: {},
    fifthDay: {}
  };

  async componentDidUpdate() {
    ********** A bunch of logic in here to extract Weather API response 
into 5 separate arrays which will each be sent to the <Day /> child components
after setting the state to those arrays(which doesn't work in this 
life-cycle method, currently) **********

  }

  render() {
    return (
      <div className="forecast">
        <Day forecast={this.state.today} />
        <Day forecast={this.state.secondDay} />
        <Day forecast={this.state.thirdDay} />
        <Day forecast={this.state.fourthDay} />
        <Day forecast={this.state.fifthDay} />
      </div>
    );
  }
}
Run Code Online (Sandbox Code Playgroud)

附言:我总是问一些复杂的问题,这些问题的答案很简单,大声笑

0xc*_*m1z 7

您可以使用componentWillReceiveProps生命周期方法。

第一个子组件呈现一些道具,例如latlng为null,然后您可以执行以下操作:

async componentWillReceiveProps(nextProps) {
  if ( this.props.lat !== nextProps.lat || this.props.lng !== nextProps.lng ) {
    const response = await YourAPICall(nextProps.lat, nextProps.lng)
    this.setState(/* set your things here */)
  }
}
Run Code Online (Sandbox Code Playgroud)

显然,这只是一个大纲...