【问题标题】:How to Add items to React Native AsyncStorage如何将项目添加到 React Native AsyncStorage
【发布时间】:2020-12-09 16:51:14
【问题描述】:

我正在构建一个应用程序,用户在其中插入任务和创建任务的时间,并且两者都保存在 react native 中的 asyncStorage 中。当将新任务添加到异步存储时,我希望 getItems() 函数同时显示上一个任务和新任务。 怎么办?

async function saveItems() {
      const items = []
              items.push(task,timestamp )
              await AsyncStorage.setItem('key', JSON.stringify(items))
          }

     async function getItems() {
          try {
            const items =  await AsyncStorage.getItem('key');
            if (items !== null) {
              console.log(JSON.parse(items));
            }      
          } catch (error) {
            console.log(error)
          }
         }

【问题讨论】:

    标签: react-native asyncstorage


    【解决方案1】:
    async function saveItems() { 
       var items = AsyncStorage.getItem('key');
       if(items)
           items.push([task,timestamp] ) 
      await AsyncStorage.setItem('key', items);
     } 
    
    async function getItems() { 
             const items = await AsyncStorage.getItem('key');
             if (items !== null)
             console.log(items);
    }
    

    Items 将是数组数组 例如:

    items = [[task1,timestamp1],[task2,timestamp2]]
    

    【讨论】:

      【解决方案2】:

      你可以做的就是为这样的任务定义一个结构

      const task = {
        description: '',
        timestamp: ''
      }
      

      现在,无论何时创建任务,您都可以将其附加到存储在 AsyncStorage 中的任务中。

      const saveItems = async() => {
        const tasks = await AsyncStorage.getItem('key');
        if(tasks != null){
          const updatedTasks = JSON.parse(tasks).append(task);
          await asyncStorage.setItem('key', JSON.stringify(updatedTasks))
        }
        else{
          await AsyncStorage.setItem('key', JSON.stringify([task]))
        }
      }
      

      现在,当您从 AsyncStorage 获取项目时,它将检索完整的任务列表

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2018-09-13
        • 1970-01-01
        • 2020-09-25
        • 2016-10-09
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多