[英]Loop through objects React
我的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"
}
]
謝謝
我相信您已經使用了花括號(可以理解),其中React實際上需要括號。 由於您是從fetch
數據的,因此請務必將構造函數也設置為“ cakes
初步對象。 嘗試這個:
constructor(props) {
super(props)
this.state = {
cakes: []
}
}
render() {
if (this.state.cakes.length > 0){
return(
<div>
{
this.state.cakes.map(cake => (
return <p>{cake.title}</p>;
))
}
</div>
);
}
return null
}
問題是,該組件被渲染和你告訴它做稱為數組的東西this.state.cakes
,但this.state.cakes
尚未確定,因為fetch
還沒有恢復。 像這樣設置構造函數,會將一個空數組傳遞給render
這樣它就不會崩潰,然后在數據加載和狀態更新時,它將隨數據一起重新渲染。
{this.state.cakes}
本身可以很好地渲染的原因是,對於組件存在的第一{this.state.cakes}
,該值是undefined
,這意味着React基本上只是忽略了它-數據加載后,呈現。 但是, map
方法失敗,因為您無法將未定義的數組傳遞給map
。
正如Ha Ja所建議的那樣,您可能應該在<p>
元素中添加一個key
屬性。
這里:
{this.state.cakes.map((cake, i) => <p key={i}>{cake.title}</p>;)}
不要忘記添加key
屬性。 Ps:最好使用唯一的Id代替數組索引。 因此,如果您對每個數組項都有一個ID,最好這樣寫:
{this.state.cakes.map(cake => <p key={cake.id}>{cake.title}</p>;)}
如果將狀態設置為獲取的結果,則由於異步操作,您可能無法立即訪問數據。 您可以通過檢查狀態來捕獲此錯誤,如果狀態沒有長度,則返回一條消息或微調器組件以指示數據的狀態。
一旦使用獲取操作中的數據更新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>
)
}
正如其他人所提到的,將key
添加到迭代元素中也是一種好習慣。
您錯過了map
內的括號
{this.state.cakes.map(cake =>{ // errors here
return <p> {cake.title} </p>;
})}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.