【问题标题】:React - Render happening before data is returned and not updating componentReact - 在返回数据并且不更新组件之前发生渲染
【发布时间】:2020-02-04 15:23:56
【问题描述】:

几个小时后我无法让它正常工作。

当创建一个需要从 Firebase 显示数据的组件时,数据会在所有操作发生后返回,因此我的组件直到再次按下按钮才能显示,该按钮再次呈现并正确显示。

目前我的函数在setState之前完成,而setState在数据返回之前发生。

当使用 setState 上的回调返回数据但组件已经呈现时,我可以得到 setState。

数据返回后如何让组件渲染?

或者正确的方法是什么?

class CoffeeList extends Component {
    constructor(props) {
        super(props);
        this.state = {
            coffeeList: [],
        }
    }

    componentDidMount() {
        this.GetCoffeeList()
    }

    GetCoffeeList() {
        var cups = []
        coffeeCollection.get().then((querySnapshot) => {
            querySnapshot.forEach(function (doc) {
                    cups.push({ name: doc.id})
            });
            console.log('Updating state')
            console.log(cups)
        })
        this.setState({ coffeeList: cups })
        console.log('End GetCoffeeList')
    }

    render() {
        const coffeeCups = this.state.coffeeList;
        console.log("Rendering component")
        return (
            <div className="coffee">
                <p> This is the Coffee Component</p>
                {coffeeCups.map((c) => {
                    return (
                        <CoffeeBox name={c.name} />
                    )
                })}
            </div >
        )
    }
}

谢谢

【问题讨论】:

    标签: reactjs firebase render setstate


    【解决方案1】:

    问题是您在解决承诺之前设置了状态。按以下方式更改代码:

      GetCoffeeList() {
      coffeeCollection.get().then((querySnapshot) => {
          const cups = []
          querySnapshot.forEach(function (doc) {
                  cups.push({ name: doc.id})
          });
          console.log('Updating state')
          console.log(cups)
          this.setState({ coffeeList: cups })
          console.log('End GetCoffeeList')
      })
    }
    

    【讨论】:

      猜你喜欢
      • 2021-12-01
      • 2019-11-18
      • 2016-06-19
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-09-21
      相关资源
      最近更新 更多