javascript 在 React Native 中循环 Json 和显示
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/34252982/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Looping Json & Display in React Native
提问by CodeGuru
How do I go about looping the result i retrieved from Json?
render: function() {
console.log(this.state.list);
contents = (
<View style={ styles.content }>
<Text>Loaded</Text>
</View>
)
return (
<View style={ styles.container }>
<View style={ styles.header }>
<Text style={ styles.headerText }>XXX</Text>
</View>
<View style={ styles.content }>
{ contents }
</View>
</View>
);
}
回答by TrungDQ
React can render an array of Elements, so you just need to construct an array and assign it to your contents
variable. I made an example using map
.
React 可以渲染一个 Elements 数组,因此您只需要构造一个数组并将其分配给您的contents
变量即可。我用map
.
render: function() {
console.log(this.state.list);
contents = this.state.list.results.map(function (item) {
return (
<View key={item.user.email} style={ styles.content }>
<Text>{item.user.email}</Text>
</View>
);
});
return (
<View style={ styles.container }>
<View style={ styles.header }>
<Text style={ styles.headerText }>XXX</Text>
</View>
<View style={ styles.content }>
{ contents }
</View>
</View>
);
}
And also: when you have an array of elements in React, you should provide a unique key
attribute to each element in the array. See why. In this case, I use item.user.email
as the unique identifier, but you can use another attribute, just make sure it unique (item.user.md5
is promising)
还有:当你在 React 中有一个元素数组时,你应该为key
数组中的每个元素提供一个唯一的属性。看看为什么。在这种情况下,我item.user.email
用作唯一标识符,但您可以使用另一个属性,只需确保它是唯一的(item.user.md5
很有希望)