如何使用AsyncStorage在数组中存储记录

时间:2016-01-07 09:27:43

标签: react-native

刚才我开始使用AsyncStorage。我尝试存储输入文本值,如下所示:

db.coll.aggregate([
    { "$project": {
        "id": 1, 
        "_id": 0, 
        "setInAnyArray": { 
            "$setIsSubset": [
                [1002], 
                { "$setUnion": [ 
                    { "$ifNull": [ "$array1", [false] ] }, 
                    { "$ifNull": [ "$array2", [true] ] }
                ] }
            ] 
        }
    }}
])

为此它正常工作,但我想将记录添加到数组中,而不是每次都更改记录。我想将记录推入一个数组,需要在视图中显示总数组数据,(即)我还需要以前可用的数据。

2 个答案:

答案 0 :(得分:30)

Stringify Array

使用JSON.stringifyJSON.parse通过AsyncStorage将数组存储为值。

存储/字符串化

const stringifiedArray = JSON.stringify(somearray)

恢复/解析

const restoredArray = JSON.parse(stringifiedArray)

AsyncStorage

的用法
 return AsyncStorage.getItem('somekey')
      .then(req => JSON.parse(req))
      .then(json => console.log(json))
      .catch(error => console.log('error!'));

const someArray = [1,2,3,4];
return AsyncStorage.setItem('somekey', JSON.stringify(someArray))
      .then(json => console.log('success!'))
      .catch(error => console.log('error!'));

答案 1 :(得分:0)

设置

     AsyncStorage.setItem('name', JSON.stringify(your array));

获取

  AsyncStorage.getItem('name', (error, result) => {
  this.setState({ name: JSON.parse(result) }, function () {   });});
相关问题