如何显示嵌套在数组中的数组?
代码:
this.props.posts
:
[
{"id":1, "name": "name01", "tags":["tag1, tag2, tag3, tag4"]},
{"id":2, "name": "name02", "tags":["tag2, tag4"]}
]
我试图展示的方式是:
renData () {
const { posts, tags } = this.props.posts
return posts.map((key, idx) => {
return (
<View key = {idx}>
<Text style={{fontSize:18}}> // <= This works if tags not mapped
{ key.id } - { key.name }
</Text>
/*
tags.map((keyTag, idp) => { //<= This does not work.
<View key = {idp}> // <= idp not defined error.
<TouchableOpacity>
<Text> {keyTag} </Text> // <= How to show the content.
</TouchableOpacity>
</View>
});
*/
</View>
)
});
}
我想在每一行显示tags
的内容。
UPDATE1:
renData () {
const { posts, tags } = this.props.tagPosts
return posts.map((post, postIndex) => {
return (
<View key = {postIndex}>
<View>
<Text style={{fontSize:18}}>
{ post.id } - { post.name }
</Text>
{
post.tags.map((tag, tagIndex) => {
<View key = {tagIndex}>
<TouchableOpacity>
<Text> {tag} </Text>
</TouchableOpacity>
</View>
})
}
</View>
)
});
}
答案 0 :(得分:2)
tags.map((keyTag, idp) => { //<= This does not work.
应该是
key.tags.map((tag, idp) => {
使用描述性名称也是一个好主意 - key
不是非常具有描述性,因此更难以遵循。尝试像
posts.map((post, index) => {
将key
重命名为post
会使您更加明显地需要访问tags
属性。
renData () {
const { posts, tags } = this.props.posts
return posts.map((post, postIndex) => {
return (
<View key = {postIndex}>
<Text style={{fontSize:18}}>
{ post.id } - { post.name }
</Text>
{
key.tags.map((tag, tagIndex) =>
<View key = {tagIndex}>
<TouchableOpacity>
<Text> {tag} </Text>
</TouchableOpacity>
</View>
);
}
</View>
)
});
}
答案 1 :(得分:2)
你应该这样做
renData () {
const { posts } = this.props // take posts from props
return posts.map((key, idx) => {
const { tags } = key // take tags from key which is single post
return (
<View key = {idx}>
<Text style={{fontSize:18}}>
{ key.id } - { key.name }
</Text>
tags.map((keyTag, idp) => {
<View key = {idp}>
<TouchableOpacity>
<Text> {keyTag} </Text>
</TouchableOpacity>
</View>
});
</View>
)
});
}
post中的标签也不是数组
[
{"id":1, "name": "name01", "tags":["tag1, tag2, tag3, tag4"]},
{"id":2, "name": "name02", "tags":["tag2, tag4"]}
]
应该是
[
{"id":1, "name": "name01", "tags":["tag1", "tag2", "tag3", "tag4"]}, // notice the quotes on each tag not around all tags as it will one element in array
{"id":2, "name": "name02", "tags":["tag2", "tag4"]}
]
答案 2 :(得分:2)
post.tags.map方法中缺少返回
renData () {
const { posts, tags } = this.props.tagPosts
return posts.map((post, postIndex) => {
return (
<View key = {postIndex}>
<View>
<Text style={{fontSize:18}}>
{ post.id } - { post.name }
</Text>
{
post.tags.map((tag, tagIndex) => {
return (
<View key = {tagIndex}>
<TouchableOpacity>
<Text> {tag} </Text>
</TouchableOpacity>
</View>
)
})
}
</View>
)
});
}
答案 3 :(得分:0)
看起来很简单,因为您没有访问tags
对象的post
。
key.tags.map((keyTag, idp) => { // ...