无法设置状态Firestore数据 [英] Can't setState Firestore data
本文介绍了无法设置状态Firestore数据的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在与Cloud Firestore一起进行React项目.我已成功从Firestore提取数据.但是我无法将状态设置为这些数据.
I'm working on a React project with Cloud Firestore. I have successfully fetched data from Firestore. But I could not set state these data to state.
如何设置这些数据的状态.
How can I set state these data.
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;
推荐答案
您应该这样设置状态,
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
});
组件首先使用初始状态进行渲染,然后首先使用项:[]
进行渲染.您必须检查是否存在数据,
Component renders first using initial state, and initially items: []
. You must check if data present,
{items && items.length > 0 && items.map(item => (
<li>
<span>{item.name}()</span>
</li>
))}
这篇关于无法设置状态Firestore数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文