【问题标题】:ReactJS / NextJS state array not rendering after setStateReactJS / NextJS 状态数组在 setState 后未呈现
【发布时间】: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


    【解决方案1】:

    您不应该手动设置状态值。您应该在调用setState 之前删除将图像设置为状态的行。该行会阻止渲染,因为之后当您使用 setState 设置状态时,react 无法检测到任何更改:

    getImages = () => {
        let firebase = loadFirebase()
        var storageRef = firebase.storage().ref('chest')
    
        storageRef.listAll().then((result) => {
            let data = []
    
            result.items.forEach((imageRef) => {
                imageRef.getDownloadURL().then((url) => {
                    data.push(url);
                    this.setState({ images: data });
                }).catch((error) => {
                    // Handle any errors
                })
            });
        }).catch((error) => {
            // Handle any errors
        })
    }
    

    【讨论】:

    • 感谢您的回答,唯一需要更改的是将this.setState({ images: data }) 移动到data.push(url) 下方,然后它就起作用了。
    • 如果提供的答案对您有用,请继续接受。这会让其他人知道它对你有用。
    猜你喜欢
    • 2021-08-17
    • 1970-01-01
    • 1970-01-01
    • 2021-01-24
    • 2017-07-23
    • 1970-01-01
    • 1970-01-01
    • 2020-01-04
    • 2019-01-19
    相关资源
    最近更新 更多