【发布时间】:2017-08-13 16:52:50
【问题描述】:
我的 React 组件有以下渲染
componentWillMount () {
var url = 'https://gist.githubusercontent.com/hart88/198f29ec5114a3ec3460/raw'
Request.get(url)
.then(data => {
this.setState({cakes: data.text});
})
}
render() {
return(
<div>
{this.state.cakes} //prints this ok
{
this.state.cakes.map(cake =>{ // error here
return <p>{cake.title}</p>;
})
}
</div>
);
}
我正在尝试遍历 this.state.cakes 这是一个对象数组。
我在这里做错了什么?
更新 - this.state.cakes 的缩写示例:
[
{
"title": "Lemon cheesecake",
"desc": "A cheesecake made of lemon",
"image":"https://s3-eu-west-1.amazonaws.com/s3.mediafileserver.co.uk/carnation/WebFiles/RecipeImages/lemoncheesecake_lg.jpg"
},
{
"title":"Banana cake",
"desc":"Donkey kongs favourite",
"image":"http://ukcdn.ar-cdn.com/recipes/xlarge/ff22df7f-dbcd-4a09-81f7-9c1d8395d936.jpg"
}
]
谢谢
【问题讨论】:
-
您遇到的错误是什么?
-
您能打印出
Cakes数组中的内容吗?因为如果它是对象数组(这在这里似乎最明显)。然后错误出现在 `{this.state.cakes}` 行而不是另一行。 -
@MinkeshJain 更新了 {this.state.cakes},
-
如何将数据加载到状态中?是否使用来自服务器的
fetch。map未定义,因为cakes还不是数组,这意味着组件无法使用数据。 -
@Spdexter -
state.cakes如何在您的组件构造函数中定义?您提供的示例是硬编码的,还是像 @Andy 建议的那样,是 fetch 的结果?
标签: javascript reactjs ecmascript-6 jsx