【发布时间】: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