微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

为什么即使我正确调用状态数组也没有设置?

如何解决为什么即使我正确调用状态数组也没有设置?

我从昨晚开始就一直在努力解决这个问题,鉴于我是一个新开发者,这非常令人沮丧。

我正在尝试将 Firebase 存储中的所有图像显示到我的 Home.js 组件内的屏幕上。我在 firebase 存储中的 "images/" 文件夹中总共有 8 张图像。我在 Home 组件中编写了此代码

export default function Home() {
  var storageRef = firebase.storage.projectStorage.ref("images");
  const [imagesArray,setimagesArray] = useState([]);
  let tempImagesArray = [];

  useEffect(() => {
    storageRef
      .listAll()
      .then((res) => {
        res._delegate.items.forEach(function (imageRef) {
          //imageRef is containing the path to each image in the storage
          projectStorage
            .ref(imageRef._location.path_)
            .getDownloadURL()
            .then((url) => {
              tempImagesArray.push(url);
              setimagesArray((oldArr) => [...oldArr,url]);
            });
        });
      })
      .then((ress) => {
        console.log(tempImagesArray.length); **// displays: 8 which is correct!**
        console.log("state array is ",imagesArray); // returns an empty array
        console.log("temp images array is  ",tempImagesArray); // returns the CORRECT array containing URL links of all the images in the storage
      })
      .catch((err) => {
        console.log(err);
      });
    //This array contains ALL the images in the images storage bucket. Now display it :)
  },[]);

奇怪的部分是有时,通常如果我在很长时间后刷新页面,上面的代码有效并且 imagesArray 包含 8 个图像但如果我再次刷新它 - 它都过去了。

如果由于任何原因,你不能给我上述问题的解决方案,你能不能给我一种方法,我可以以某种方式使用 tempImagesArray 它不是一个状态数组来迭代链接显示它们Home 组件中的用户

PS:考虑到设置状态数组(imagesArray),我尝试了另外两种设置方法

setimagesArray(tempImagesArray) 

setimagesArray([...imagesArray,url])

PPS:既然有人重复了这个问题 - 这个问题如何与据说已经有答案的承诺问题相关联?当所有承诺都得到解决时,我不会尝试做任何事情,我正在尝试正确设置我的数组状态!这两者是如何联系在一起的?

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。