gpt4 book ai didi

javascript - 循环遍历对象 React

转载 作者:行者123 更新时间:2023-11-28 17:50:33 26 4
gpt4 key购买 nike

我的 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"
}
]

谢谢

最佳答案

如果状态设置为提取的结果,由于异步操作,您可能无法立即访问数据。您可以通过检查状态来捕获这一点,如果状态没有长度,则返回一条消息或一个旋转组件以指示数据正在传输中。

一旦使用获取操作中的数据更新了 state.cakes,组件将重新渲染。

constructor(props) {
super(props);
this.state = { cakes: [] };
}

componentDidMount() {
fetch('/cakes')
.then(res => res.json())
.then(cakes => this.setState({ cakes }));
}

render() {
if (!this.state.cakes.length) return <Spinner />
return (
<div>
{this.state.cakes.map(cake => {
return <p>{cake.title}</p>;
})};
</div>
)
}

正如其他人提到的,添加 keys 也是一个很好的做法。到您的迭代元素。

关于javascript - 循环遍历对象 React,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45662710/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com