Can't setState Firestore data

放肆的年华 提交于 2021-02-10 04:58:33

问题


I'm working on a React project with Cloud Firestore. I have successfully fetched data from Firestore. But I could not set state these data to state.

How can I set state these data.

class App extends Component {
  constructor(props) {
    super(props);
    this.state = {
      items: []
    };
  }

  async componentDidMount() {
    const items = [];

    firebase
      .firestore()
      .collection("items")
      .get()
      .then(function(querySnapshot) {
        querySnapshot.forEach(function(doc) {
          items.push(doc.data());
        });
      });

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

  render() {
    const items = this.state.items;
    console.log("items", items);

    return (
      <div>
        <div>
          <ul>
            {items.map(item => (
              <li>
                <span>{item.name}()</span>
              </li>
            ))}
          </ul>
      </div>
    );
  }
}

export default App;

回答1:


You should set state like this,

firebase
   .firestore()
   .collection("items")
   .get()
   .then((querySnapshot) => {  //Notice the arrow funtion which bind `this` automatically.
       querySnapshot.forEach(function(doc) {
          items.push(doc.data());
       });
       this.setState({ items: items });   //set data in state here
    });

Component renders first using initial state, and initially items: []. You must check if data present,

{items && items.length > 0 && items.map(item => (
      <li>
          <span>{item.name}()</span>
      </li>
))}


来源:https://stackoverflow.com/questions/57508459/cant-setstate-firestore-data

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!