【问题标题】:Can't 'map' an array in array of objects correctly in reactjs无法在 reactjs 中正确“映射”对象数组中的数组
【发布时间】:2019-11-11 10:27:48
【问题描述】:

我的 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 ;) ) )

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

我该怎么做?

【问题讨论】:

    标签: javascript arrays reactjs object ecmascript-6


    【解决方案1】:

    执行tags={post.tags.map(xTag =&gt; { return xTag ; })} 等价于tags={post.tags}。所以影响最终格式的相关代码在 Post 组件中。所以tags.join(', ')tags.map(t =&gt; '#'+t).join(' ') 都可以。

    【讨论】:

      【解决方案2】:

      您可以为标签创建一个单独的组件并为其设置样式。 然后改写这一行:

      tags={post.tags.map(xTag => {
          return <Tag>{xTag}</Tag>;  // or <Tag content={xTag} />
      })}
      

      【讨论】:

        【解决方案3】:

        如果你想将你的标签数组转换成一个字符串,有几个选项取决于你想要的格式:

        使用简单的连接,您的格式会受到限制:(您可以传入将附加在每个条目之后的字符,例如 .join(' ') 仅用于空格)

        post.tags.join() // Returns 'react,javascript'
        

        使用reduce 函数,您可以进一步控制字符串的格式:

        post.tags.reduce((string, tag) => string += `${tag} `, '')
        

        要更改格式,只需编辑附加的字符串${tag}

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2022-12-01
          • 2021-02-04
          • 2017-05-14
          • 2022-06-17
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2017-08-18
          相关资源
          最近更新 更多