React native 如何使用setState在react native中保存当前位置?
我使用此代码从用户处获取当前位置,但现在我在使用setState将纬度和经度保存到州时收到了一条通知 ReferenceError:未定义setStateReact native 如何使用setState在react native中保存当前位置?,react-native,React Native,我使用此代码从用户处获取当前位置,但现在我在使用setState将纬度和经度保存到州时收到了一条通知 ReferenceError:未定义setState 如何将位置保存到状态?您可以使用此设置状态 在构造函数中添加状态变量 constructor(props) { super(props); this.state = { ... lat: 0.000, long: 0.000,
如何将位置保存到状态?您可以使用
此
设置状态
在构造函数中添加状态变量
constructor(props) {
super(props);
this.state = {
...
lat: 0.000,
long: 0.000,
...
};
}
然后将此
添加到方法中
async componentDidMount(){
const { status } = await Expo.Permissions.askAsync(Expo.Permissions.LOCATION);
if (status === 'granted') {
const location = await Expo.Location.getCurrentPositionAsync({
enableHighAccuracy: true,
});
this.setState({
lat:JSON.stringify(location.coords.latitude),
long:JSON.stringify(location.coords.longitude),
});
}
}
因为当您的componentDidMount状态不存在时,请在构造函数中使用类似于this.lat和this.long的变量,并使用this.setState…设置它。。。。而不仅仅是setState()。。。。。如果你已经定义了状态
async componentDidMount(){
const { status } = await Expo.Permissions.askAsync(Expo.Permissions.LOCATION);
if (status === 'granted') {
const location = await Expo.Location.getCurrentPositionAsync({
enableHighAccuracy: true,
});
this.setState({
lat:JSON.stringify(location.coords.latitude),
long:JSON.stringify(location.coords.longitude),
});
}
}