【发布时间】: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')})。如果没有await或then,您在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) });