首页 > 解决方案 > 在道具更改时对 axios 发布请求和 setState 做出反应

问题描述

我有一个反应应用程序,我正在使用地理定位来获取用户位置。

按照初始化说明,我包装了组件:

export default geolocated({
    positionOptions: {
        enableHighAccuracy: true,
    },
    userDecisionTimeout: 15000,
})(ShowPois);

一旦用户接受(允许)在浏览器上查找位置,我希望发生两件事。

首先,当应用程序可以使用位置时,我需要设置一个标志,所以我有这个:

static getDerivedStateFromProps(props, state) {
        if (!state.geolocatedReady && props.coords) {
            return {
                geolocatedReady: true
            }
        }
        return null;
    }

注意 props.coords 来自 geolocated

第二件事是我想用找到的位置的地址完成一个输入框。为了做到这一点,我必须向 api 发出发布请求以获取地址,但问题是我不能使用 getDerivedStateFromProps() 方法,因为该方法必须返回一个值,而不是一个承诺(由 axios 发布请求发出) .

那么如何在组件中的 prop 更改时发出 post 请求,然后设置状态?

标签: javascriptreactjsaxios

解决方案


getDerivedStateFromProps仅适用于边缘情况。你这里的情况听起来很适合componentDidUpdate

componentDidUpdate() {
  if(!this.state.geolocatedReady && this.props.coords) {
    this.setState({
      geolocatedReady: true,
    });
    this.getAddress(this.props.coords);
  }
}
getAddress = async (coords) => {
  const address = await mapApi.getAddress(coords);
  // or whatever you want with it.
  this.setState({
   address 
  })
}

推荐阅读