如何在反应中渲染 object 数组?
how to render object array in react?
这是我的 componentDidmount
componentDidMount() {
for ( var i in course ) {
let title = course[i];
const ref = firestore.collection('courses');
ref.where("class", "array-contains", course[i]).get()
.then(querySnapshot => {
const count = querySnapshot.size
course_stats.push({
title: title,
value: count,
});
});
}
console.log(course_stats)
this.setState({
courses: course_stats,
})
}
这是我的渲染图
render() {
const { classes } = this.props;
if (this.state.courses) {
console.log(this.state.courses)
return (
<ul>
{course_stats.map(d => <li key={d.title}>{d.title}</li>)}
</ul>
)
}
在行 console.log 上,我可以看到其中的 object 数组。但是,当我尝试渲染它时,它没有显示任何内容。
this is the console.log capture
如何渲染数组的标题和值?
谢谢!
添加到 izb 的答案中,this.setState
已经执行,所以你应该使用 async/await,或者添加一个单独的回调函数,例如 returns a Promise
setAsync(state) {
return new Promise((resolve) => {
this.setState(state, resolve)
});
}
handleChange = (event) => {
return this.setAsync({[event.target.name]: event.target.value})
}
这是我的 componentDidmount
componentDidMount() {
for ( var i in course ) {
let title = course[i];
const ref = firestore.collection('courses');
ref.where("class", "array-contains", course[i]).get()
.then(querySnapshot => {
const count = querySnapshot.size
course_stats.push({
title: title,
value: count,
});
});
}
console.log(course_stats)
this.setState({
courses: course_stats,
})
}
这是我的渲染图
render() {
const { classes } = this.props;
if (this.state.courses) {
console.log(this.state.courses)
return (
<ul>
{course_stats.map(d => <li key={d.title}>{d.title}</li>)}
</ul>
)
}
在行 console.log 上,我可以看到其中的 object 数组。但是,当我尝试渲染它时,它没有显示任何内容。 this is the console.log capture
如何渲染数组的标题和值? 谢谢!
添加到 izb 的答案中,this.setState
已经执行,所以你应该使用 async/await,或者添加一个单独的回调函数,例如 returns a Promise
setAsync(state) {
return new Promise((resolve) => {
this.setState(state, resolve)
});
}
handleChange = (event) => {
return this.setAsync({[event.target.name]: event.target.value})
}