React useState 不更新 Array.map 函数内的值

时间:2021-01-25 13:47:54

标签: 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
        .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) 时,上面的代码在第一次迭代/间隔时工作正常,我得到了预期的结果,但在第二次迭代/间隔后,我只得到了第一个或前一个结果。

1 个答案:

答案 0 :(得分:1)

状态正在更新,但间隔函数不知道此更新。要在 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,
            },
          ],
        },
      },
    ];
  }
});