【问题标题】:React axios post request and setState on props change在道具更改时对 axios 发布请求和 setState 做出反应
【发布时间】:2020-02-13 17:35:49
【问题描述】:

我有一个 react 应用,我正在使用 geolocated 来获取用户位置。

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

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 发布请求发出) .

那么我怎样才能发出一个 post 请求,然后在组件中的 prop 发生变化时设置状态呢?

【问题讨论】:

    标签: javascript reactjs axios


    【解决方案1】:

    getDerivedStateFromProps 仅适用于edge cases。你这里的案例听起来很适合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 
      })
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-03-14
      • 1970-01-01
      • 2017-12-11
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-02-04
      • 2022-12-10
      相关资源
      最近更新 更多