简体   繁体   English

在 React 中从 state 数组渲染项目时出错

[英]Error rendering item from state array in React

I have a problem getting state data in the render function.我在渲染 function 中获取 state 数据时遇到问题。 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.您只设置一项,因此items实际上只是一项并且items[0]失败。

this.setState({
  items: data
});    

should be inside the .then() so that it only runs after all the items are populated with the .forEach() .应该在 .then .then()内,以便它仅在所有项目都填充有.forEach()后运行。

Update your componentDidMount() like so:像这样更新您的componentDidMount()

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM