试图理解使用 AsyncStorage 获取本地 storay 的原生反应



我无法控制台记录组件中保存的存储值。

这是基本的反应原生页面:

import React from 'react';
import { AsyncStorage, StyleSheet, Text, View } from 'react-native';
const SavedExercise = (props) => {
const getStoredExercises = async () => {
const saved = await AsyncStorage.getItem('@storage_Key');
return saved;
// try {
//   const saved = await AsyncStorage.getItem('@storage_Key');
//   return saved;
// } catch (e) {
//   // saving error
// }
};
return (
<View>
<Text>hello</Text>
{saved}
</View>
);
};
const style = StyleSheet.create({
});
export default SavedExercise;

我尝试了许多不同的方法来尝试控制台记录(或输出(保存的@storage_key值。这应该是一个对象,但保存在一个字符串中,最终必须 JSON.parse 它。但我只是想让它记录下来。不幸的是没有运气。

我不断收到这样的错误:

Objects are not valid as a React child (found: object with keys {_40, _65, _55, _72}). If you meant to render a collection of children, use an array instead.

Warning: Functions are not valid as a React child. This may happen if you return a Component instead of <Component /> from render. Or maybe you meant to call this function rather than return it.%s,

如何正确获取存储在@storage_key中的对象?

首先,import { AsyncStorage } from 'react-native';已被弃用,你可以签入文档rn-deprecated-asyncstorage。

所以现在你应该安装 rn-异步存储 .

之后在你的代码中,你在哪里设置异步存储值,比如AsyncStorage.setItem('@storage_Key', 'stored value'),只是一个快速说明,yoou 只能将字符串值保存在异步存储中,如果你想保留数组或其他东西,你需要先 JSON.stringify 它,当通过const value = await AsyncStorage.getItem('@storage_Key')提取时,你需要再次 JSON.parse 值以转换为数组或任何你想要的格式。

试试这个。我相信该错误是由于您使用已弃用的异步存储造成的。尝试使用我提供链接的那个.r

希望对您有所帮助。 随意怀疑。

最新更新