reactjs 通过react native在javascript中使用数组时遇到问题

cunj1qz1  于 2023-03-17  发布在  React
关注(0)|答案(2)|浏览(162)

代码

let allurl = []
const [toReadurl, setToReadurl] = useState([])
useEffect(() => {

  
  const listRef = sRef(storage, paramKey)

  
  // Find all the prefixes and items.
    listAll(listRef)
    .then((res) => {
      res.prefixes.forEach((folderRef) => {
        // All the prefixes under listRef.
        // You may call listAll() recursively on them.
      });
      res.items.forEach((itemRef) => {
        // All the items under listRef.
        //console.log(itemRef)
        getDownloadURL(itemRef).then((url =>{
          //console.log(url)
          allurl.push(url)
          setToReadurl(allurl)
          //console.log(toReadurl)
          
        }))
      });
    }).catch((error) => {
      // Uh-oh, an error occurred!
      console.log(error)
    });
  }, [])

    console.log(toReadurl)

如果将console.log(toReadurl)放在useEffect()之外,则数组中只有2个元素

但是如果我把它放在函数和useEffect()中,数组中会有4个元素

为什么在useEffect()之后我的数组项减少了2?
我如何保存4个链接,以便我可以显示出来?

icnyk63a

icnyk63a1#

你可以使用setToReadurl的回调函数,你会收到最新的/先前的值,并且可以简单地返回一个包含先前值和新url的新数组。
这将允许您移除allUrl并仅使用状态,因为allUrl值将在每次渲染时重置。

const [toReadurl, setToReadurl] = useState([]);

useEffect(() => {
  const listRef = sRef(storage, paramKey);

  // Find all the prefixes and items.
  listAll(listRef)
    .then((res) => {
      res.prefixes.forEach((folderRef) => {
        // All the prefixes under listRef.
        // You may call listAll() recursively on them.
      });
      res.items.forEach((itemRef) => {
        // All the items under listRef.
        getDownloadURL(itemRef).then((url) => {
          setToReadurl((prevValues) => {
            return [...prevValues, url];
          });
        });
      });
    })
    .catch((error) => {
      // Uh-oh, an error occurred!
      console.log(error);
    });
}, []);

console.log(toReadurl);
qlfbtfca

qlfbtfca2#

验证码:

// Initialize allurl to an empty array
let allurl = []

// Initialize toReadurl state to an empty array
const [toReadurl, setToReadurl] = useState([])

useEffect(() => {
  const listRef = sRef(storage, paramKey)

  listAll(listRef)
    .then((res) => {
      res.prefixes.forEach((folderRef) => {
        // All the prefixes under listRef.
        // You may call listAll() recursively on them.
      });
      res.items.forEach((itemRef) => {
        getDownloadURL(itemRef).then((url => {
          // Push the new URL to allurl array
          allurl.push(url)
          // Update toReadurl state with the new array
          setToReadurl([...allurl]) // use spread operator to create a new array
        }))
      });
    }).catch((error) => {
      console.log(error)
    });
}, [])

// Use console.log inside a useEffect hook to log the updated value of toReadurl after each state update
useEffect(() => {
  console.log(toReadurl)
}, [toReadurl])

相关问题