【问题标题】:AsyncStorage.removeItem is not removing the itemAsyncStorage.removeItem 未删除该项目
【发布时间】:2021-12-27 00:19:01
【问题描述】:

有很多问题可用,我尝试了大约 12 种不同的方法,但没有一种方法有效。最有效的是:

  async function removeItemValue(key) {
    try {
      await AsyncStorage.removeItem(key);
      return true;
    }
    catch (exception) {
      return false;
    }
  }

那我叫它:

  useEffect(() => {
    removeItemValue('@cartInfo');  
  }, []);

我尝试将它放在useEffect 钩子之外,但仍然没有效果。我做错了什么?


更新:

也试过了,但没用:

  useEffect(() => {
    removeItemValue('@cartInfo').then(() => { console.log('removed') })
  }, []);

也试过了

  useEffect(() => {
    AsyncStorage.removeItem('@cartInfo', () => {
      AsyncStorage.getItem('@cartInfo').then((res) => {
        console.log("RES IS: " + res);
      })
    })
  }, []);

仍然没有运气。我正在使用 @react-native-community/async-storage 的 v1.12.1

【问题讨论】:

  • 你不是在等待removeItemValue()useEffect() 中的结果,你需要removeItemValue().then(() => { console.log('removed')})。如果没有awaitthen,您在removeItemValue 中的代码将无法运行
  • 我做的和removeItemValue('@cartInfo').then(() => { console.log('removed') }) 完全一样,但它不起作用。即使我可以看到removed 正在控制台中打印,但值仍然存在。
  • 你能发布更多上下文吗?您可能不会等到它被删除才能访问该值。如果您尝试获取 then 子句中的值会发生什么,即 removeItemValue('@cartInfo').then(() => { console.log('removed'); AsyncStorage.getItem('@cartInfo').then(console.log); })
  • @Abe 这样做会打印removed,然后打印我要删除的值,即@cartInfo 中的值。这意味着即使正在执行 remove 子句,它也不会被删除。对于更多上下文,我不确定要添加什么,其中有一个字符串值,我只想在某个时候将其删除。
  • 好的,那么听起来removeItemValue 可能不起作用。如果你这样做AsyncStorage.removeItem('@cartInfo', () => { AsyncStorage.getItem('@cartInfo').then(console.log) });

标签: react-native asyncstorage


【解决方案1】:

正如我们在chat 中讨论的那样,AsyncStorage.removeItem 实际上是有效的,问题是setItem 被过于频繁地调用,因此该值在稍后在getItem 中被读取之前被替换。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-02-15
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多