【问题标题】:ReactJS+FireStore Data mapping issueReactJS+FireStore 数据映射问题
【发布时间】:2018-06-13 21:11:10
【问题描述】:

我正在编写一个小程序来从 Firestore 数据库中获取类别并在网页中显示为列表。

我的代码如下所示:

class Category extends Component {
  constructor() {
    super();
    this.state = {'Categories': []}
  }
  render() {
    let categoryList = null;
    if (Array.isArray(this.state.Categories)) {
      console.log(this.state.Categories);
      categoryList = this.state.Categories.map((category) =>  {
        return <li>{category.name}</li>
      });
    }
    return(
      <ul>{categoryList}</ul>
    );
  }
  componentWillMount() {
    // fetch the data from the Google FireStore for the Category Collection
    var CategoryCollection = fire.collection('Category');
    let categories = [];
    CategoryCollection.get().then((snapshot)=> {
      snapshot.forEach ((doc) => {
        categories.push(doc.data());
      });
    }).catch((error) => {
      console.log("Error in getting the data") 
    });
    this.setState({'Categories': categories});
  }
}

我能够获取数据甚至填充 this.state.Categories,但是 map 函数没有被执行。

console.log 语句生成一个值数组,但渲染中的 map 函数没有被执行。有什么想法吗?

Console.log 输出:

【问题讨论】:

  • 嗨!您的代码工作正常:codesandbox.io/s/9j27k0zrxp(抱歉,我已经清理了一下)。此外,我建议在 HOC 或渲染道具组件中获取数据,并将其留作演示目的,以便分离中心

标签: reactjs typescript firebase google-cloud-firestore


【解决方案1】:

您在处理数据检索时出错。在最后一行中,categories 仍然是空的,因此它使用空数据集触发 setState。应该是什么谎言

componentWillMount() {

    fire.collection('Category').get()
        .then(snapshot => {
            const categories = snapshot.map(doc => doc.data());
            // sorry, but js object should be pascal cased almost always
            this.setState({ categories }); 
         })
         .catch(error => {
             console.log("Error in getting the data") 
         });

}

【讨论】:

    【解决方案2】:

    仅在数据存在时才返回数据。最简单的方法是将&lt;ul&gt;{categoryList}&lt;/ul&gt; 替换为&lt;ul&gt;{this.state.categories &amp;&amp; categoryList}&lt;/ul&gt;

    【讨论】:

      【解决方案3】:

      我可以通过一个小改动让它工作(将 this.setState 移到回调内部)。老实说,我仍然不明白其中的区别。

      P.S:我来自 PHP 开发,这是我进入 ReactJS 的第一步。

      componentWillMount() {
      
          // fetch the data from the Google FireStore for the Category Collection
          var categoryCollection = fire.collection('Category');
          let categories = [];
          categoryCollection.get().then((snapshot)=> {
              snapshot.forEach ((doc) => {
                  categories.push(doc.data());
              }); 
              if (categories.length > 0) {
                  this.setState({'Categories': categories});
              }
          }).catch((error) => {
             console.log("Error in getting the data"); 
          });
          // this.setState({'Categories': categories});
      
      }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2017-12-26
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多