我正在编写一个小程序来从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,但是map函数没有被执行。
console.log语句生成一个值数组但渲染中的map函数未执行。有什么想法吗?
答案 0 :(得分:1)
处理数据检索时出错。在最后一行中,类别仍为空,因此它会触发带有空数据集的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")
});
}
答案 1 :(得分:1)
如果数据存在,则仅返回数据。最简单的方法是将<ul>{categoryList}</ul>
替换为<ul>{this.state.categories && categoryList}</ul>
答案 2 :(得分:0)
我可以通过一个小的更改使其工作(将this.setState移动到回调中)。老实说,我还是不明白其中的区别。
P.S:我来自PHP开发,这是我进入ReactJS的第一步。
UPDATE account_type
SET type_id = 3
FROM user
WHERE user.account_id = account_type.account_id AND
user.username LIKE 'filter%';