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

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

我正在 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',
        })
arrays react-native asyncstorage
1个回答
2
投票

稍后回复

不,你所期待的事情是无法实现的 AsyncStorage仅以键值对的形式存储数据。所以暴露的API AsyncStorage仅适用于字符串数据,您需要解析JSON 进行逻辑和字符串化并设置为 AsyncStorage 再次。

删除单个项目

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
});

参考:

删除项目方法
多重删除方法

© www.soinside.com 2019 - 2024. All rights reserved.