在本机反应中格式化从 asyncStorage 检索的数据
Formatting data retrieved from asyncStorage in react native
我在 'react-native' 应用程序中通过 @react-native-async-storage/async-storage
将一些数据存储在 asyncStorage
中。当我拉回数据时,我想将结果分配给一个下拉菜单列表,它需要这种格式:
names = [{name: 'Dave'}, {name: 'Julio'}];
现在,当我提取 asyncStorage 数据并应用 JSON.parse()
时,它看起来像这样:
jsonNames: Array [
"{\"name\":\"Chris\"}",
"{\"name\":\"Janet\"}",
"{\"name\":\"Augustine\"}",
]
这是我检索数据的函数:
getNames = async () => {
try {
const jsonNames = await AsyncStorage.getItem('names')
return jsonNames != null ? JSON.parse(jsonNames) : null;
} catch(e) {
console.log(e);
}
}
是否有我可以使用的功能来清理它,使其成为我需要的格式,如上所述?
要转换它,请执行这样的添加步骤
const jsonNames = [
"{\"name\":\"Chris\"}",
"{\"name\":\"Janet\"}",
"{\"name\":\"Augustine\"}",
];
console.log(jsonNames.map(x => JSON.parse(x)))
此外,您可以查看在 AsyncStorage
中保存此值的方式,看起来您在保存之前分别序列化数组中的每个对象,而不是一次序列化整个数组。
看起来您已经将数据存储为 JSON,您可以更改它以避免解析 JSON 的新步骤。无论如何,如果您想按原样处理数据,您可以这样做:
const jsonNames = [
"{\"name\":\"Chris\"}",
"{\"name\":\"Janet\"}",
"{\"name\":\"Augustine\"}",
];
const names = jsonNames.map(JSON.parse)
我在 'react-native' 应用程序中通过 @react-native-async-storage/async-storage
将一些数据存储在 asyncStorage
中。当我拉回数据时,我想将结果分配给一个下拉菜单列表,它需要这种格式:
names = [{name: 'Dave'}, {name: 'Julio'}];
现在,当我提取 asyncStorage 数据并应用 JSON.parse()
时,它看起来像这样:
jsonNames: Array [
"{\"name\":\"Chris\"}",
"{\"name\":\"Janet\"}",
"{\"name\":\"Augustine\"}",
]
这是我检索数据的函数:
getNames = async () => {
try {
const jsonNames = await AsyncStorage.getItem('names')
return jsonNames != null ? JSON.parse(jsonNames) : null;
} catch(e) {
console.log(e);
}
}
是否有我可以使用的功能来清理它,使其成为我需要的格式,如上所述?
要转换它,请执行这样的添加步骤
const jsonNames = [
"{\"name\":\"Chris\"}",
"{\"name\":\"Janet\"}",
"{\"name\":\"Augustine\"}",
];
console.log(jsonNames.map(x => JSON.parse(x)))
此外,您可以查看在 AsyncStorage
中保存此值的方式,看起来您在保存之前分别序列化数组中的每个对象,而不是一次序列化整个数组。
看起来您已经将数据存储为 JSON,您可以更改它以避免解析 JSON 的新步骤。无论如何,如果您想按原样处理数据,您可以这样做:
const jsonNames = [
"{\"name\":\"Chris\"}",
"{\"name\":\"Janet\"}",
"{\"name\":\"Augustine\"}",
];
const names = jsonNames.map(JSON.parse)