【发布时间】:2018-06-13 21:11:10
【问题描述】:
我正在编写一个小程序来从 Firestore 数据库中获取类别并在网页中显示为列表。
我的代码如下所示:
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,但是 map 函数没有被执行。
console.log 语句生成一个值数组,但渲染中的 map 函数没有被执行。有什么想法吗?
【问题讨论】:
-
嗨!您的代码工作正常:codesandbox.io/s/9j27k0zrxp(抱歉,我已经清理了一下)。此外,我建议在 HOC 或渲染道具组件中获取数据,并将其留作演示目的,以便分离中心
标签: reactjs typescript firebase google-cloud-firestore