我在 React 组件中有一个方法,可以从 API 获取一些数据
this.state.matches 首先返回一个空数组
loadMatches() {
let matches = this.state.matches;
forEach(this.state.matchIds.splice(0,5), matchid => {
axios.get(url)
.then(function (response) {
matches.push(response.data)
})
});
this.setState({
matches
})
}
然后是一个将数据映射到 React 组件的方法
renderMatch() {
return this.state.matches.map((match, index) => {
return (
<Match
key={index}
gameId={match.gameId}
/>
);
});
}
renderMatch() 在我的渲染方法中使用 {this.renderMatch()}
进行调用
但没有任何内容被渲染,如果我调用 .length 它只会返回 0,即使我可以在 devtools 中看到该数组包含 5 个对象。
数组中的硬编码对象被渲染
最佳答案
您正在改变状态,因此 React 不会触发新的渲染。您应该创建一个新数组,而不是推送状态:
loadMatches() {
let promises = [];
forEach(this.state.matchIds.splice(0,5), matchid => {
promises.push(axios.get(url).then(res => res.data));
});
Promise.all(promises).then(matches => {
this.setState({
matches
});
});
}
编辑以处理异步。
关于javascript - 在 React 中渲染对象数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49045677/