无法设置State Firestore 数据

k10*_*10a 3 firebase reactjs google-cloud-firestore

我正在使用 Cloud Firestore 开发 React 项目。我已成功从 Firestore 获取数据。但我无法将这些数据设置为state。

我如何设置状态这些数据。

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;
Run Code Online (Sandbox Code Playgroud)

rav*_*l91 5

你应该这样设置状态,

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
    });
Run Code Online (Sandbox Code Playgroud)

组件首先使用初始状态进行渲染,并且最初使用items: []. 您必须检查数据是否存在,

{items && items.length > 0 && items.map(item => (
      <li>
          <span>{item.name}()</span>
      </li>
))}
Run Code Online (Sandbox Code Playgroud)