删除AsyncStorage中特定项目的最佳方法

时间:2018-06-29 12:56:29

标签: arrays react-native asyncstorage

我要在AsyncStorage中存储对象数组,并想知道删除特定对象的最佳方法。现在,我将id传递给函数,然后遍历数组以匹配id并删除对象,然后更新AsyncStorage中的数组。这似乎可以正常工作,但是我想知道这是否是最佳选择,或者是否有更好的方法来做到这一点?

我现在的功能:

  export function removeData(id) {

    AsyncStorage.getItem('@books')
    .then((books) => {
    const updatedBooks = (JSON.parse(books))

        for (let i = 0; i < updatedBooks.length; i++) {
           if(updatedBooks[i].id == id) {
              updatedBooks.splice(i, 1);
          }
      }
      AsyncStorage.setItem('@books', JSON.stringify(updatedBooks));

   })
}

我向AsyncStorage添加数据的功能:

    export function addData(book) {

    AsyncStorage.getItem('@books')
    .then((books) => {
    const b = books ? JSON.parse(books) : [];
    b.push(book);
    AsyncStorage.setItem('@books', JSON.stringify(b));
  });  
}

添加带有示例数据的数据以显示结构的按钮:

  <Button 
        title = "Add book"
        onPress={() => addData({
            id: 1,
            title: 'Harry Potter',
            author:'J.K. Rowling',
            thumbnail:'https://covers.openlibrary.org/w/id/7984916-M.jpg',
        })

1 个答案:

答案 0 :(得分:0)

要删除单个项目

AsyncStorage.removeItem('key', (err) => {
  // key 'key' will be removed, if they existed
  // callback to do some action after removal of item
});

要删除多个项目

let keys = ['k1', 'k2'];
AsyncStorage.multiRemove(keys, (err) => {
  // keys k1 & k2 removed, if they existed
  // callback to do some action after removal of item
});

参考:

RemoveItem method
MultiRemove method