【发布时间】:2020-08-27 01:49:18
【问题描述】:
我在 React / NextJS 中使用 .map() 渲染我的对象时遇到问题。
我有一个从 Firebase Cloud Storage 获取图像的功能,代码如下:
getImages = () => {
let firebase = loadFirebase()
var storageRef = firebase.storage().ref('chest')
let { state } = this
storageRef.listAll().then((result) => {
let data = []
result.items.forEach((imageRef) => {
imageRef.getDownloadURL().then((url) => {
data.push(url)
}).catch((error) => {
// Handle any errors
})
})
state.images = data
this.setState({ images: data })
}).catch((error) => {
// Handle any errors
})
}
这部分似乎可以正常工作,因为我确实取回了数据并更新了状态,结果如屏幕截图所示: Results after setState
然后我使用以下代码映射图像:
{ this.state.images.map((image, index) => {
return (
<img
key={ index }
src={ image }
alt=""
/>
)
})}
在与此相同的页面上,我还有其他地方可以从 Firebase 获取数据,相应地设置我的状态并使用 .map() 呈现对象。在这些情况下,它工作得非常好。不同之处在于,在这些情况下,我使用 getInitialProps() 从 Firebase 获取数据,而对于来自 Cloud Storage 的数据,我有一个函数 getImages() 函数,在 componentDidMount()
上调用但在这两种情况下,状态都是在 componentDidMount() 中设置的,并且最终结果返回 this.state em> 看起来像附上的屏幕截图。
对此的任何帮助和/或改进将不胜感激。
【问题讨论】:
标签: javascript reactjs firebase firebase-storage next.js