简体   繁体   English

响应 axios post request 和 setState on props 更改

[英]React axios post request and setState on props change

I have a react app and I am using geolocated to get users location.我有一个反应应用程序,我正在使用地理定位来获取用户位置。

Following the instructions for the initialization I have wrapped the component:按照初始化的说明我已经包装了组件:

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

As soon as the user accepts (allows) the location finding on the browser I want two things to happen.一旦用户接受(允许)在浏览器上查找位置,我希望发生两件事。

First I need to set a flag when then location is available to the app, so I have this:首先,当应用程序可以使用位置时,我需要设置一个标志,所以我有这个:

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

Notice that props.coords comes from geolocated注意 props.coords 来自 geolocated

The second thing is that I want to complete an input box with the address of the location found.第二件事是我想用找到的位置的地址来完成一个输入框。 In order to do this I have to do a post request to an api to get the address, but the problem is I cannot use the getDerivedStateFromProps() method because the method must return a value, not a promise (made by axios post request).为了做到这一点,我必须向 api 发出一个 post 请求来获取地址,但问题是我不能使用 getDerivedStateFromProps() 方法,因为该方法必须返回一个值,而不是一个承诺(由 axios 发布请求) .

So how can I make a post request and then set the state when a prop changes in the component?那么如何在组件中的 prop 更改时发出 post 请求,然后设置状态?

getDerivedStateFromProps is only for edge cases . getDerivedStateFromProps仅适用于边缘情况 The case you have here sounds like a fit for componentDidUpdate .你在这里的情况听起来很适合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 
  })
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM