javascript - 在道具更改时对 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 请求,然后设置状态?
解决方案
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
})
}
推荐阅读
- azure-webjobs - azure webjobs - '需要会话的实体不可能创建非会话消息接收器
- excel - 查找月份的最后一天
- javascript - highcharts + vue.js 的问题:测量的特定图表
- java - 修改Android Java源码并重新打包成APK文件
- python - 如何处理函数的返回值?
- python - 在 Python 语言中,“x”代表什么,尤其是在“for”语句中?
- javascript - 为什么 Javascript 的 regex.lastIndex 对于不同的正则表达式表现不同?
- c++ - 在 C/C++ 中移动代码块(低级)
- laravel - Laravel 管理文件路径
- xamarin.ios - iOS Xamarin 中的文件上传