【发布时间】:2018-08-06 06:16:04
【问题描述】:
我一直试图从我的 api 中获取数据,但不知何故,this.state.Data.map 确实有效,但参数 dynamicdata 未定义。
在App.js 反应
class ShowAll extends Component {
constructor(props){
super(props);
this.state = {
Data: [],
}
}
componentDidMount(){
Request.get('/budget').then((res)=>{
let DataString = JSON.stringify(res.body);
this.setState({
Data: DataString
}, function(){
console.log(DataString);
})
}).catch((err)=> console.log(err));
}
render(){
return(
<div>
{
this.state.Data.map(function(dynamicData, key){
<div>{dynamicData[0]._id}</div> // doesn't render anything and throws an error message saying TypeError: Cannot read property '_id' of undefined
})
}
</div>
)
}
}
**编辑 1 **
api数据结构是
[{
"_id":"lul",
"_creator":"5a8f8ecdd67afa6494805bef",
"firstItem":"hero",
"secondItem":"30",
"thirdItem":"3",
"__v":0,
"tBudget":9,
"thirdPrice":3,
"secondPrice":3,
"firstPrice":3
}]
【问题讨论】:
-
您的服务器返回了什么?也许
res.body不是可迭代对象?不知道res.body的值很难猜到 -
res.body确实返回了我想要的数据。我使用console.log()进行了检查。一切都很好,但我无法访问对象的特定项目。检查后编辑的结构 api 中的每个对象都有这个结构。我正在尝试访问 _id 或其中的任何内容 -
总的来说,问题似乎出在 api 的响应上。
Array.from期望一个类似数组或可迭代的对象。检查here -
您能否提供从 API 调用中获取的数据的结构
-
第一个问题是
map内的数据形状假设(数组项内没有[0]属性),这就是引发无法读取属性错误的原因。修复此问题后,您需要从map返回 jsx 元素,并在此 jsx 元素上包含key属性。阅读特殊属性keyhere