首页 > 解决方案 > 如何在 onpress 处于活动状态时将位置数据存储到 Asyncstorage

问题描述

所以基本上我想在按下按钮处于活动状态时将位置数据存储到异步存储中。我已经阅读了 asyncstorage 文档,但是我仍然卡住并且仍然需要一些提示和更多示例来进行编码。

有人能帮我吗?

export default class index extends Component {
  findCoordinates = () => {
    Geolocation.getCurrentPosition(
      (position) => {
        const location = JSON.stringify(position);
        this.setState({ location });
      },
      (error) => Alert.alert(error.message),
      {
        enableHighAccuracy: true,
        timeout: 20000,
        maximumAge: 1000,
        forceRequestLocation: true,
      }
    );
  };

  render() {
    return (
      <Container>
        <ScrollView>
          <View style={styles.top}></View>
          <Card
            containerStyle={{
              borderRadius: 10,
              marginTop: -30,
            }}
          >
            <View>
              <TouchableOpacity onPress={this.findCoordinates}>
                <Text>Find My Coords?</Text>
                <Text>Location: {this.state.location}</Text>
              </TouchableOpacity>
            </View>
          </Card>
        </ScrollView>
      </Container>
    );
  }
}

标签: javascriptreact-native

解决方案


假设您已经导入了以下内容:


import {AsyncStorage} from 'react-native';

点击按钮后请添加以下代码:


AsyncStorage.setItem('storedlocation', this.state.location);

 

下一次,如果你想获取 asyncstorage 的值,说进入“retrievedlocation”的状态,请使用以下代码:


  getstoredlocationFunction = () => {

    AsyncStorage.getItem('storedlocation').then(

      value2 =>

        this.setState({ retrievedlocation: value2 })

    );

  };

祝你今天过得愉快。


推荐阅读