简体   繁体   中英

Error rendering item from state array in React

I have a problem getting state data in the render function. It works fine and returns the array when I use

console.log(items)

But trying to get first item from the array yields an error

console.log(items[0])

Full code is:

import React from "react";
import StatsSection from "./../components/StatsSection";
import { db } from "./../util/database";

class IndexPage extends React.Component {

  constructor(props) {
    console.log(props)
    super(props);
    this.state = {};
  }

  componentDidMount() {

    var data = []
    db.collection('test')
      .get().then(snapshot => {
        snapshot.forEach(doc => {
          data.push(doc.data())
        })
      })

    this.setState({
      items: data
    });    
  }

  render() {
    const { items } = this.state
    console.log(items[0])


    return (

      <StatsSection
        color="white"
        size="medium"
        backgroundImage=""
        backgroundImageOpacity={1}
        items={[

          {
            title: "Following",
            stat: "123"
          },
          {
            title: "Followers",
            stat: "456k"
          },
          {
            title: "Likes",
            stat: "789"
          }
        ]}
      />
    );
  }
}

export default IndexPage;

Where am I making the mistake?

You're only setting one item, so items is actually just one item and items[0] fails.

this.setState({
  items: data
});    

should be inside the .then() so that it only runs after all the items are populated with the .forEach() .

Update your componentDidMount() like so:

componentDidMount() {
  db.collection('test').get().then(snapshot => {
    var data = []
    snapshot.forEach(doc => {
      data.push(doc.data())
    })
    this.setState({ items: data })  
  })
}

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