【问题标题】:Can't setState Firestore data无法设置状态 Firestore 数据
【发布时间】:2019-08-15 10:44:31
【问题描述】:

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

如何设置状态这些数据。

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;

【问题讨论】:

  • 仅供参考,反引号是为了说明代码位,而不是为了强调或突出产品名称。

标签: reactjs firebase google-cloud-firestore


【解决方案1】:

你应该这样设置状态,

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

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

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

【讨论】:

  • 非常感谢!我能做到!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2020-09-26
  • 2020-04-01
  • 2021-01-02
  • 2021-06-06
  • 1970-01-01
  • 2019-04-14
  • 1970-01-01
相关资源
最近更新 更多