javascript - react ,在父组件中异步调用后使用 Prop 更新子组件中的状态

标签 javascript reactjs async-await state

我正在构建一个天气应用程序,我正在寻找一些建议,以了解在父组件进行异步调用后,根据从父组件发送的 Prop 更新子组件中的状态的最佳做法。

我有一个父组件,它在 componentDidMount() 方法中对 navigator.geolocation 进行异步/等待调用,并返回我要发送的纬度和经度作为 Prop 传递给子组件。然后,在子组件中,我需要使用 Prop 中的纬度和经度对 OpenWeatherMap API 进行异步/等待调用。然后我需要使用 responsesetState()。我不能在 child 中使用 componentDidMount(),因为它会在父 async/await 调用返回之前挂载。

问题在于应用程序流程:父组件挂载和渲染,将 props 作为 null 发送给子组件。子组件使用 null 属性进行挂载和渲染。然后,async/await 在 parent 中返回一个响应,在 componentDidMount() 中将响应设置为 latlong,parent 重新 -使用正确的值如 latlong 渲染并发送 Prop 给 child 。子组件更新为 props 中的正确值。现在,在这一点上我需要使用这些 Prop 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>
    );
  }
}

子组件:

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>
    );
  }
}

附言我总是问一些复杂的问题,但答案很简单,哈哈

最佳答案

您可以使用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 */)
  }
}

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

关于javascript - react ,在父组件中异步调用后使用 Prop 更新子组件中的状态,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54498462/

相关文章:

html - 将 <a> 链接定位在具有响应行为的 <image> 上

reactjs - 使用 React 传递动态 url

c# - 如何在 lambda 中选择期间等待

javascript - 在 javascript 中模拟 <enter> 按键以触发表单提交

javascript - Bootstrap : Using panel heading to collapse panel body

JavaScript 无法在另一个函数中调用原型(prototype)函数

javascript - 节点 v12.6.0 中 array.reverse() 的问题

c# - 多线程异步模式

.net - 为什么WCF的自动生成代理有sync方法?

javascript - onchange 事件委托(delegate)以附加文本字段