AsyncStorage getItem() 永远不会 return null

AsyncStorage getItem() doesn't return null ever

我在 React Native 应用程序中使用 AsyncStorage 并且(如果我对文档的理解正确的话)如果没有为给定键存储任何内容,getItem() 方法应该 return null。

来自文档:

getItem() ... Returns:如果给定键存在条目,则承诺使用字符串值解析,否则为 null。“

但是,每当我为新密钥获取数据时,它永远不会为空。我的 getItem 函数位于 useEffect 挂钩中,用于在第一次渲染之前尝试加载数据。

useEffect(() => {
  getData();
}, []);

 const storeData = async () => {
    try {
      setMyInfo({...})
      const jsonInfo = JSON.stringify({myInfo})
      await AsyncStorage.setItem(storage_Key, jsonInfo)
      alert('Data successfully saved')
    } catch (e) {
      alert('Failed to save the data to the storage')
    }
  }

const getData = async () => {
  try {
    let data = await AsyncStorage.getItem(storage_Key);
    if (data !== null) {
      setMyInfo(JSON.parse(data));
    } else {
      alert("test");
    }
  } catch (e) {
    alert("Failed to fetch the data from storage");
  }
};

myInfo,变量是一个 JSON 对象,它实际上似乎用“Useless Placeholder”填充了所有值。像这样:

myInfo = {
  value1: "Useless Placeholder",
  value2: "Useless Placeholder",
};

我目前的解决方案:

即使 getItem() 函数在 useEffect 钩子内部,myInfo 变量在开始时对于 half second 是未定义的。所以如果定义了变量,我有一个三元运算符来显示值。

<Text>{typeof myInfo === 'undefined' ? '' : myInfo.value1}</Text>

如果我只是尝试显示 myInfo.value1,它会抛出一个 'myInfo is undefined' 错误。但是,这样,即使在为指定键存储任何数据之前,打开此页面时也会出现“Useless Placeholder”值。

这对我现在有用,但如果能提供一些关于如何实际使用 asynstorage 的指导,我们将不胜感激。

我明白是怎么回事了。

事实证明,在存储数据时,useState 变量没有被设置为新值。我发现如果我尝试触发 storeData 函数两次,它实际上会正确保存数据。因此,为了解决这个问题,我将 storeData 函数更改为以下内容:

 const storeData = async () => {
    try {
      const jsonRnfo = JSON.stringify({
         value1: value,
         value2: value, ....
      })
      await AsyncStorage.setItem(storage_Key, jsonInfo)
      alert('Data successfully saved')
    } catch (e) {
      alert('Failed to save the data to the storage')
    }
  }

我没有使用 AsyncStorage.setItem() 来存储来自 useState 的数据,而是在我的 storeData 函数中构建了一个新的 JSON 对象。 useState 仍在应用程序中用于前端目的。