我有一个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来自地理位置
第二件事是,我想用找到的位置的地址填写一个输入框。为此,我必须向api发送请求以获取地址,但是问题是我不能使用getDerivedStateFromProps()方法,因为该方法必须返回一个值,而不是诺言(由axios发布请求) 。
那我该如何发出发布请求,然后在道具更改组件时设置状态?
答案 0 :(得分: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
})
}