这是来 self 的 Drupal 站点的 json:
[
{
title: "I believe every human has a finite number of heartbeats. I don't intend to waste any of mine.",
uid: "gestor"
},
{
title: "Man must explore, and this is exploration at its greatest",
uid: "gestor"
}
]
它有两个用方括号分隔的元素 {} 这就是我尝试在我的 React 组件中使用 Fetch 的方式。
componentWillMount(){
// Con fetch me conecto al site de Drupal
fetch('http://rest.dd:8080/all-of-us')
.then(response => response.json())
.then(postPrvSrv => {
// A cada post lo coloco en un array
console.log(postPrvSrv.results)
postPrvSrv.results.forEach(post => {
let data = {
title:post.title,
author:post.uid
}
console.log(data);
// Actualizamos el state para poder renderizar
this.setState({postPrvSrv:this.state.postPrvSrv.concat([data])})
})
})
}
这是我的控制台日志结果:
console.log(postPrvSrv.results)
= undefined
console.log(data);
= Nothing,因为它在 forEach
console.log(this.state.postPrvSrv.length)
= 0。
这是错误信息:
Unhandled Rejection (TypeError): Cannot read property 'forEach' of undefined
来自控制台的错误:
Uncaught (in promise) TypeError: Cannot read property 'forEach' of undefined
最佳答案
如果您直接从 Durpal 端点返回一个数组,那么 postPrvSrv
变量(在您的获取响应处理程序中)将是一个普通数组。
假设 postPrvSrv
是一个数组,那么 postPrvSrv
上的 .results
字段将是 undefined
。
这就是您将收到 “无法读取未定义的属性 'forEach'” 错误的原因 - 您正在尝试调用 .forEach(..)
在 .results
字段上,它在 postPrvSrv
数组中未定义。
要解决此问题,请尝试按照以下评论所示调整您的代码:
fetch('http://rest.dd:8080/all-of-us')
.then(postPrvSrv => {
console.log(postPrvSrv) // Fix this line to see log of data in console
postPrvSrv.forEach(post => { // Fix this line
let data = {
title:post.title,
author:post.uid
}
console.log(data);
this.setState({postPrvSrv:this.state.postPrvSrv.concat([data])})
})
})
关于javascript - 为什么我的数组是空的? React 读取 json api,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51579704/