首页 > 解决方案 > AsyncStorage 不会在组件加载时增加值

问题描述

我正在使用 AsyncStorage 和 React Native。我有一个在 useEffect 中调用的函数并且它可以工作,但是我的 AsyncStorage 值没有得到更新。它说“1”。我将 AsyncStorage 作为数组,我也尝试过这种传统方式,并且值不会在负载时增加。我已经在 IOS 模拟器和 IOS 设备上进行了测试,但没有运气。下面是在 useEffect((),[]) 中运行的函数

 const addFunction = async () => {
        var storage_array = await AsyncStorage.getItem(ASYNC_STORAGE_KEY);

         try {
           if(storage_array) {
             storage_array = JSON.parse(storage_array);
             let flow_complete = 0;
             flow_complete++;
             storage_array.push(flow_complete);
             //storage_array.push(flow_test);
             console.log('THIS IS flow_complete', flow_complete);
             console.log('THIS IS THE ASYNCSTORAGE', storage_array);
           } else {
            flow_complete = 0;
            console.log('Storage array is empty')
           }
         } catch (error) {
           console.log(error);
         }
      }

标签: javascriptreactjsreact-nativeasynchronous

解决方案


您需要设置项目以更新存储。

const addFunction = async () => {
        var storage_array = await AsyncStorage.getItem(ASYNC_STORAGE_KEY);
         try {
           if(storage_array) {
             storage_array = JSON.parse(storage_array);
             let flow_complete = 0;
             flow_complete++;
             storage_array.push(flow_complete);
             //storage_array.push(flow_test);
             console.log('THIS IS flow_complete', flow_complete);
             console.log('THIS IS THE ASYNCSTORAGE', storage_array);
             AsyncStorage.setItem(ASYNC_STORAGE_KEY, JSON.stringify(storage_array));
           } else {
            flow_complete = 0;
            console.log('Storage array is empty')
           }
         } catch (error) {
           console.log(error);
         }
      }

推荐阅读