8

我想在AsyncStorage.setItem里面使用AsyncStorage.getItem。如何以正确的方式做到这一点?

我的代码如下:

createVehicle: function (vehicle, cb) {
    AsyncStorage.getItem('vehicle')
    .then(json => {

        let vehicles = [];

        if (json) {
            vehicles = JSON.parse(json);
            let o_vehicle = filter(vehicles, {autralis_id: vehicle.autralis_id});
            if (o_vehicle.length > 0) {
                cb(o_vehicle[0].id);
                return;
            } else {
                vehicles.push(vehicle);
            }
        } else {
            vehicles.push(vehicle);
        }
        AsyncStorage.setItem('vehicle', JSON.stringify(vehicles), () => {
            cb(vehicle.id + 1)
        });
    }).done();
},

这是正确的方法吗?

4

4 回答 4

9

我创建了一个存储服务,可以在需要时通过传递所需的参数在整个项目中使用。看一看 :

export default {
async setItem(key, value) {
    try {
        return await AsyncStorage.setItem(key, JSON.stringify(value));
    } catch (error) {
        // console.error('AsyncStorage#setItem error: ' + error.message);
    }
},
async getItem(key) {
    return await AsyncStorage.getItem(key)
        .then((result) => {
            if (result) {
                try {
                    result = JSON.parse(result);
                } catch (e) {
                    // console.error('AsyncStorage#getItem error deserializing JSON for key: ' + key, e.message);
                }
            }
            return result;
        });
},
async removeItem(key) {
    return await AsyncStorage.removeItem(key);
}
}

这是迄今为止我遇到的最佳实践。你也应该使用它。

于 2017-04-29T19:45:53.607 回答
1
import React, { Component } from 'react'
import { StatusBar } from 'react-native'
import { AsyncStorage, Text, View, TextInput, StyleSheet } from 'react-native'
class AsyncStorageExample extends Component {
   state = {
      'name': ''
   }
   componentDidMount = () => AsyncStorage.getItem('name').then((value) => this.setState({ 
'name': value }))
   setName = (value) => {
      AsyncStorage.setItem('name', value);
      this.setState({ 'name': value });
   }
   render() {
      return (
     <View style = {styles.container}>
        <TextInput style = {styles.textInput} autoCapitalize = 'none'
        onChangeText = {this.setName}/>
        <Text>
           {this.state.name}
        </Text>
     </View>
      )
   }
}
export default AsyncStorageExample
const styles = StyleSheet.create ({
   container: {
      flex: 1,
      alignItems: 'center',
      marginTop: 50
   },
   textInput: {
      margin: 5,
      height: 100,
      borderWidth: 1,
      backgroundColor: '#7685ed'
   }
})
于 2019-07-26T05:24:36.650 回答
1

请参考这个官方文档,它使用getIteminside setItem,所以我想你也可以使用setIteminside getItem,因为返回值只是and的一个PromisegetItemsetItem

AsyncStorage.setItem('UID123', JSON.stringify(UID123_object), () => {
  AsyncStorage.mergeItem('UID123', JSON.stringify(UID123_delta), () => {
    AsyncStorage.getItem('UID123', (err, result) => {
      console.log(result);
    });
  });
});
于 2017-04-29T17:13:52.820 回答
0

我不知道我是不是来得太晚了,但我是为自己写的:

import { Base64 } from 'js-base64';
import { AsyncStorage } from 'react-native';

export async function storeItem(key: string, item: string, isJson: boolean) {
    try {
        return new Promise(async resolve => {
            let stringObject = '';
            if (isJson) {
                stringObject = JSON.stringify(item);
            } else {
                stringObject = item.toString();
            }
            let base64Object = await Base64.encode(stringObject);
            await AsyncStorage.setItem(key, base64Object);
            resolve();
        });
    } catch (e) {
        console.log(e);
    }
}

export async function retrieveItem(key: string, isJson: boolean) {
    try {
        return new Promise(async resolve => {
            let base64Item = await AsyncStorage.getItem(key);
            if (base64Item === null) {
                resolve(null);
            }
            let item = await Base64.decode(base64Item);
            resolve(isJson ? JSON.parse(item) : item);
        });
    } catch (e) {
        console.log(e);
    }
}

export async function removeItem(key: string) {
    try {
        return new Promise(async resolve => {
            await AsyncStorage.removeItem(key);
            resolve();
        });
    } catch (e) {}
}

由于特殊字符,我使用 base64。

希望它可以帮助:)

于 2019-09-25T14:34:50.947 回答