我正在编写一个小程序来从Firestore DB中获取类别并在网页中显示为列表。
我的代码看起来像这样:
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,但是地图功能没有被执行。
console.log语句生成一个值数组,但渲染中的map函数未执行。有什么想法吗?
处理数据检索时出错。在最后一行中,类别仍为空,因此它会触发带有空数据集的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")
});
}
仅在数据存在时才返回数据。最简单的方法是用<ul>{categoryList}</ul>
替换<ul>{this.state.categories && categoryList}</ul>
我可以使用一个小的更改(将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});
}