Apparently no causes for the error "TypeError: Cannot read properties of undefined "

Apparently no causes for the error "TypeError: Cannot read properties of undefined "

我必须在布局中显示我从数据库中获取的一些数据。这是我用来获取数据的代码:

    const [array, setArray] = useState([])
    const collectionRef = collection(db, "Collection")
    const q = query(collectionRef, orderBy("Order", "desc"))

    useEffect(() => {
      auth.onAuthStateChanged(function (user) {
      if (user) {
             onSnapshot(q, (data) =>
             setArray(data.docs.map((doc) => ({ ...doc.data(), id: doc.id })))
         );
      }
    })
   }, [auth]);

下面是html

    <div> 
        <h2>{array[0].Name}</h2>
    </div>

最让我困惑的是错误并不总是出现,有时一切正常,有时它会在没有明显原因的情况下停止工作。如果我对数组执行 console.log 有时它会打印数据并且一切正常,有时它会打印一个空数组并且什么也不做。 我声明该数组从未被修改,它在代码的开头加载并且仅读取数据。

array 对于第一个渲染和所有其他渲染都是空的,直到返回数据。尝试类似的东西:

<div> 
    <h2>{array.length && array[0].Name}</h2>
</div>