在本机反应中擦除 AsyncStorage

Wipe AsyncStorage in react native

我注意到我在调试 redux 我在 react-native[=] 中坚持 AsyncStorage 的操作上浪费了一定的时间20=] 感谢 redux-persist。有时我只想擦除 AsyncStorage 以节省一些开发时间并尝试使用新数据。

编辑:最好的情况下解决方案应该在模拟器和真实设备上工作,iOS 和 Android。也许不同的平台有不同的解决方法。

谢谢

尝试使用 clear() 功能擦除所有客户端、库等的所有 AsyncStorage

redux-persist 带有一个 purge() 回调。如果您愿意,可以在某处的调试菜单中调用它。

clearAsyncStorage = async() => {
    AsyncStorage.clear();
}

此函数可应用于代码库的任何位置以清除 AsyncStorage。例如,这里是如何在 <Button> 组件上调用它。

<Button onPress={this.clearAsyncStorage}>
  <Text>Clear Async Storage</Text>
</Button>

您可以轻松清除 AsyncStorage,而无需触及您的源代码。使用 react native debugger;并在 devtools 控制台类型

$reactNative.AsyncStorage.clear();

或者用 clear() 在 RN 的普通调试器中调用它,你可以把它放在...

if (__DEV__) {
   global.clear = () => {
     AsyncStorage.clear().then(() => console.log('Cleared'))
   }
}

恕我直言,所有关于 AsyncStorage.clear() 的答案都是错误的,因为正如 documentation 所说:

Erases all AsyncStorage for all clients, libraries, etc. You probably don't want to call this; use removeItem or multiRemove to clear only your app's keys.

可能会找到正确答案:

Here is a simple way of doing it:

clearAllData() {
    AsyncStorage.getAllKeys()
        .then(keys => AsyncStorage.multiRemove(keys))
        .then(() => alert('success'));
}

使用 AsyncStorage 在我这边引发了引用错误:

ReferenceError: AsyncStorage is not defined

我终于在 React Native Debuguer 中找到了 documentation 提及

$reactNative.*

(对于 RN >= 0.56)

导致此代码段清除我所有本地存储的意思:

clearAllData = () => {
    $reactNative.AsyncStorage.getAllKeys()
        .then(keys => $reactNative.AsyncStorage.multiRemove(keys))
        .then(() => alert('success'));
}

然后 clearAllData();