UI 不会在状态更改时更新 [英] UI does not update on state change
问题描述
我正在使用 react native maps 并在 componentDidMount()
上要求用户启用他们的位置.
I am using react native maps and on componentDidMount()
asking user to enable their location.
componentDidMount() {
if (Platform.OS === 'android') {
RNAndroidLocationEnabler.promptForEnableLocationIfNeeded({ interval: 20000, fastInterval: 5000 })
.then(data => {
console.log(data);
this.findingLocation();
}).catch(err => {
});
}
else if (Platform.OS === 'ios') {
this.findingLocation();
}
}
在 findingLocation()
中,我试图像这样获取用户的当前位置
And in findingLocation()
I am trying to get the current location of user like this
findingLocation = () => {
Geolocation.getCurrentPosition(
position => {
this.setState({
region: {
latitude: position.coords.latitude,
longitude: position.coords.longitude,
latitudeDelta: 0.0043,
longitudeDelta: 0.0034,
}
}, () => {
console.warn(this.state.region);
});
},
error => console.warn('Error', JSON.stringify(error)),
{ enableHighAccuracy: true, timeout: 20000, maximumAge: 10000 },
);
}
在控制台中,我得到了当前位置的纬度.但有时它不会反映在 UI 上.
And in console I am getting lat long of current location. But it does not reflect on UI sometimes .
界面代码
<MapView
provider={PROVIDER_GOOGLE}
style={styles.map}
region={this.state.region}
onRegionChangeComplete={this.onRegionChange}
zoomEnabled={true}
showsUserLocation={true}
zoomControlEnabled={true}
showsMyLocationButton={true}
/>
我使用的库是 https://github.com/react-用于 MAP & 的 native-community/react-native-mapshttps://www.npmjs.com/package/@react-native-GEOLOCATION 的社区/地理位置.
请帮帮我.我哪里出错了.提前致谢.
Help me please. Where I am going wrong. Thanks in advance.
推荐答案
在 setState 函数中使用展开运算符.至于为什么,请阅读这篇文章:https://medium.com/pro-react/a-brief-talk-about-immutability-and-react-s-helpers-70919ab8ae7c
Use the spread operator in your setState function. As for why, read this article: https://medium.com/pro-react/a-brief-talk-about-immutability-and-react-s-helpers-70919ab8ae7c
this.setState(prevState => ({
region: {
...prevState.region
latitude: position.coords.latitude,
longitude: position.coords.longitude,
latitudeDelta: 0.0043,
longitudeDelta: 0.0034,
}
}), () => {
console.warn(this.state.region);
})
这篇关于UI 不会在状态更改时更新的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!