Reactjs React useState未更新Array.map函数中的值
更新array.map内的状态时遇到问题。 我想做的是,我从firestore获取数据,并使用下面的登录名Reactjs React useState未更新Array.map函数中的值,reactjs,react-native,react-hooks,use-state,Reactjs,React Native,React Hooks,Use State,更新array.map内的状态时遇到问题。 我想做的是,我从firestore获取数据,并使用下面的登录名 const [storedImages, setStoredImages] = useState([]); (async () => { setInterval(async () => { await friends.map(async key => { const getImagesFromStore= await db .co
const [storedImages, setStoredImages] = useState([]);
(async () => {
setInterval(async () => {
await friends.map(async key => {
const getImagesFromStore= await db
.collection('users')
.doc(key) //XYZ
.collection('uploadedImages')
.get();
const userExistsInList = (users, user) => { //checks if the user exists in storedImages
return users?.hasOwnProperty(user);
};
const newStoryAlreadyInStories = (allImages, newImage) => { //checks if image already exists in the storedImages
return allImages.find(s => s.id === newImage.id);
};
const appendStory = (originalObject, userId, imageToAppend) => {
return {
...originalObject,
[userId]: {
...originalObject[userId],
uploadedImages: originalObject[userId].uploadedImages.concat({
id: imageToAppend.id,
img: imageToAppend.data().image,
timestamp: imageToAppend.data().createdAt,
}),
},
};
};
if (getImagesFromStore && getImagesFromStore.docs.length !== 0) {
if (storedImages.length !== 0) {
const newState = storedImages.map(user => {
if (userExistsInList(user, key)) {
let updatingStory;
getImagesFromStore.docs.forEach(story => {
const found = newStoryAlreadyInStories(stories, story);
if (!found) {
//User is already in state and the new story is not in the list
updatingStory = appendStory(user, key, story);
}
});
return updatingStory;
} else {
//User is not in the list yet
}
});
setStoredImages(newState);
} else {
await getImagesFromStore.docs.map(async image => {
const getUsersDetail = await db
.collection('users')
.doc(key)
.get();
setStoredImages([
{
[key]: {
name: getUsersDetail.data().name,
displayPic: getUsersDetail.data().profileAvtar,
uploadedImages: [
{
id: image.id,
img: image.data().image,
timestamp: image.data().createdAt,
},
],
},
},
]);
});
}
}
});
}, 10000);
})();
当我使用console时,上述代码在第一次迭代/间隔期间运行良好。log(storedImages)我得到了预期的结果,但在第二次迭代/间隔之后,我只得到了第一次或以前的结果。状态正在更新,但间隔函数不知道此更新。要在
setInterval
/setTimeout
函数中获取当前状态值,可以使用setStoredImages
回调函数:
setStoredImages((prev) => {
if (prev.length !== 0) {
//--> your logic
return newState;
} else {
//--> else logic
return [
{
[key]: {
name: getUsersDetail.data().name,
displayPic: getUsersDetail.data().profileAvtar,
uploadedImages: [
{
id: image.id,
img: image.data().image,
timestamp: image.data().createdAt,
},
],
},
},
];
}
});
如果使用此逻辑,则会抛出未定义的storedImages错误,因为setStoredImages未等待其中的值,当使用参数async(prev)=>时,您需要对代码应用更改以使其正常工作。另一个解决方案是创建一个ref来存储当前状态,但我将使用它作为最后一个资源。有没有办法将状态存储在ref中?用上面的业务逻辑来实现它?