我使用AsyncStorage
存储了以下对象数组:
[
{
"groupId": 1,
"id": 1,
"name": "a",
},
{
"groupId": 2,
"id": 2,
"name": "ab",
},
{
"groupId": 3,
"id": 3,
"name": "abc",
},
{
"groupId": 2,
"id": 4,
"name": "abcd",
},
]
我正在检索数据以在Flatlist中显示它,但不是显示groupId
,我想显示每个项目的groupName
。
我有另一个键与组存储:
[
{
"groupName": "g1",
"id": 1,
},
{
"groupName": "g2",
"id": 2,
}
]
我编写了一个基于groupId
检索groupName
的函数。
const getGroupName = async (groupIdToFind) => {
const existingsGroups = (await AsyncStorage.getItem("groups")) || "[]";
const existingsGroupsParsed = JSON.parse(existingsGroups);
const groupDataFound = existingsGroupsParsed.find(
(results) => results.id.toString().indexOf(groupIdToFind) > -1
);
if (groupDataFound) {
return groupDataFound.groupName;
}
return false;
};
我想修改从我的loadFlatlist
函数中存储检索到的数据,但这就是我正在努力的地方。
const loadFlatlist = async (storageKey) => {
try {
let itemsOnStorage = await AsyncStorage.getItem(storageKey);
itemsOnStorage = JSON.parse(itemsOnStorage);
if (itemsOnStorage !== null) {
let finalItemsOnStorage = "";
itemsOnStorage.map(async function (obj) {
console.log(obj.groupId); // Correctly returns 1, 2, 3 ...
let retrievedGroupName = await getGroupName(obj.groupId);
console.log(retrievedGroupName); // Correctly returns g1, g2 ...
finalItemsOnStorage = await update(itemsOnStorage, {
groupId: { $set: retrievedGroupName },
});
});
console.log(finalItemsOnStorage); // Returns same content as itemsOnStorage
setDataOnDevice(itemsOnStorage); // This will be loaded in my flatlist
}
} catch (err) {
alert(err);
}
};
问题是在loadFlatlist
,我没有设法用groupName
代替groupId
。finalItemsOnStorage
与itemsOnStorage
内容相同。
你能看出我的函数出了什么问题吗?有更好的方法吗?
试一下
const loadFlatlist = async (storageKey) => {
try {
let itemsOnStorage = await AsyncStorage.getItem(storageKey);
itemsOnStorage = JSON.parse(itemsOnStorage);
const existingsGroups = (await AsyncStorage.getItem("groups")) || "[]";
const existingsGroupsParsed = JSON.parse(existingsGroups);
if (itemsOnStorage !== null) {
let finalItemsOnStorage = [];
itemsOnStorage.forEach(item => {
let index = existingsGroupsParsed.findIndex(obj => obj.id ===
item.groupId)
if(index != -1) {
finalItemsOnStorage.push({...item,
groupId:existingsGroupsParsed[index].groupName})
}
});
console.log(finalItemsOnStorage);
setDataOnDevice(finalItemsOnStorage);
}
} catch (err) {
alert(err);
}
};