【发布时间】:2019-01-10 15:42:52
【问题描述】:
我目前正在使用 MERN 堆栈创建一个全堆栈应用程序,但遇到了一个以前没有遇到的问题。当我使用 .map() 函数迭代我的数组时,即使控制台记录了我的数组存在,长度为 4,并且具有所有正确的元素(它们是对象),我的数组没有被.map() 函数迭代。
我还注意到,当我在控制台登录 array.length 时,我的值为零 - 尽管在之前的日志中我被告知该数组的长度为 4(它应该如此)。
下面是我填充数组的地方:
getTournaments(){
fetch("http://localhost:3001/tournament", {
credentials: 'include',
method: "get",
headers: {
'Accept':'application/json',
'Content-Type': 'application/json',
}
})
.then( (response) => response.json())
.then( (response) => {
if(response){
response.map((tournament)=> {
this.state.tournaments.push(tournament);
})
}
})
}
我在这里打电话给getTournaments():
componentDidMount(){
this.getTournaments(); ...
这就是我尝试映射数组的方式:
this.state.tournaments.map((tournament,index) => {
return (<div key={index}> {tournament.title} </div>);
})
最后,我的控制台日志是在我调用渲染函数时创建的。 这是渲染函数:
renderSpectatorView(){
var array = [1,2,3];
var currentTournaments = this.state.tournaments;
// console.log(currentTournaments);
return(
<div className="page-wrapper">
{/* BOOTSTRAP MODAL */}
{this.state.isAuth ? <Button onClick={this.goToCreate} bsStyle="primary">Create Tournament</Button> : null}
<div className="tournament-wrapper">
{
console.log(this.state.tournaments)}
{ console.log(this.state.tournaments.length)}
</div>
</div>
);
}
我在项目早期使用了几乎相同的方法(但更复杂,因为我迭代了数组中每个对象的属性),所以我很难理解为什么这不起作用。我最初的想法是,在我完成从我的 API 获取数据之前,可能正在调用渲染函数 - 但值记录正确。
我应该使用 Promise 还是 async/await 来实现这一点,以确保仅在收集数据后才进行渲染?感谢您的任何帮助。
【问题讨论】:
-
您在第一次 sn-p 中尝试映射时,
response的值是多少? -
问题是
this.state.tournaments.push(tournament);。您必须使用 setState 来触发重新渲染
标签: javascript arrays reactjs ecmascript-6