如何使用setState在react native中保存当前位置?

问题描述 投票:0回答:1

我使用此代码从用户获取当前位置,但现在我在使用setState来保存纬度和经度状态时会有通知。

ReferenceError:未定义setState

 async componentDidMount(){
     const { status } = await Expo.Permissions.askAsync(Expo.Permissions.LOCATION);
       if (status === 'granted') {
           const location = await Expo.Location.getCurrentPositionAsync({
             enableHighAccuracy: true,
           });
           setState({
             lat:JSON.stringify(location.coords.latitude),
             long:JSON.stringify(location.coords.longitude),
           });
       }
 }

如何将位置保存到州?

react-native
1个回答
1
投票

你可以用this setState。

在你的constructor添加状态变量,

constructor(props) {
        super(props);
        this.state = {
            ...
            lat: 0.000,
            long: 0.000,
            ...
        };
    }

然后将this添加到方法中。

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),
           });
       }
 }
© www.soinside.com 2019 - 2024. All rights reserved.