首页 > 解决方案 > 无法在 reactjs 中正确“映射”对象数组中的数组

问题描述

我的 JSON“虚拟”后端中有一组对象(这里只有一个,但没关系)。在每个对象中,我都有一个属性“tags”,其中还包含简单的数组,让我给你看一个例子

[
 {
  "title": "Get up and run",
  "author": "Johnny",
  "tags": ["react", "javascript"]
 }
]

我试图映射一个给我结果的数组:(见代码)

Article title: Get up and run
Writer: Johnny
Tags: reactjavascript

但我想得到这样的结果:

Article title: Get up and run
Writer: Johnny
Tags: react javascript (or "react, javascript" or "#react #javascript")

似乎我无法同时正确映射“标记”数组和对象的主数组。:( 你能帮我吗?

class Content extends Component {
 state = {
    posts: []
}

componentDidMount () {
    axios.get("json-file.json")
    .then(response => {
            this.setState({posts: response.data.map(post => {
                return post; /*here I get the whole data from dummy 
backend */
            })})
        }
    )
}

render () {
    const post = this.state.posts.map(post => {
        return <Post 
            title={post.title} 
            date={post.date} 
            author={post.author}
            tags={post.tags.map(xTag => {
                return xTag ;
            })} /* I have other Component which correctly renders this... 
 no worries here */
            />
    })

    return (
        <div>
            {post}
        </div>
    )
}
}

我期望更好的数组“映射”我尝试得到这样的结果

文章标题:起床奔跑作者:约翰尼

Tags: react javascript (or "react, javascript" or "#react #javascript") 

代替

Tags: reactjavascript

或者

Tags: ["react", "javascript"] (it was the worst version :)(its fixed ;) ) )

我想同时正确地映射一个对象数组和“标签”数组,

我怎样才能做到这一点?

标签: javascriptarraysreactjsobjectecmascript-6

解决方案


tags={post.tags.map(xTag => { return xTag ; })}相当于tags={post.tags}。所以影响最终格式的相关代码在 Post 组件中。所以要么做tags.join(', ')要么tags.map(t => '#'+t).join(' ')


推荐阅读