简体   繁体   中英

ReactJS / NextJS state array not rendering after setState

I am having trouble rendering my objects using .map() within React / NextJS.

I have a function where I get images from Firebase Cloud Storage, code below:

    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
        })
    }

This part seems to work as I do get data back and the state is updated, results as in screenshot: Results after setState

I then map through images with the code below:

{ this.state.images.map((image, index) => {
 return (
    <img
      key={ index }
      src={ image }
      alt=""
    />
  )
})}

On the same page as this, I have other places where I get data from Firebase, set my states accordingly and render the objects using .map() . In those cases it works perfectly fine. Difference is that in those cases I use getInitialProps() to get my data from Firebase, whereas with the data from Cloud Storage I have a function, the getImages() function above, that is called on componentDidMount()

But in both cases the state is set in componentDidMount() and the final result returned of this.state looks like the screenshot attached.

Any help and / or improvements on this will be much appreciated.

You should never set the state values manually. You should just remove the line that sets the images in the state before calling setState . That line prevents the rendering since after that react can not detect any changes when you set the state using setState :

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
    })
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM