Javascript Can';t';地图';reactjs中对象数组中的数组
在我的JSON“虚拟”后端中有一个对象数组(这里只有一个,但这并不重要)。 在每个对象中,我都有一个属性“tags”,它也包含一个简单的数组,让我向您展示一个示例Javascript Can';t';地图';reactjs中对象数组中的数组,javascript,arrays,reactjs,object,ecmascript-6,Javascript,Arrays,Reactjs,Object,Ecmascript 6,在我的JSON“虚拟”后端中有一个对象数组(这里只有一个,但这并不重要)。 在每个对象中,我都有一个属性“tags”,它也包含一个简单的数组,让我向您展示一个示例 [ { "title": "Get up and run", "author": "Johnny", "tags": ["react", "javascript"] } ] 我试图映射一个数组,结果是:(参见代码) 但我想得到这样的结果: Article title: Get up and run Writer: J
[
{
"title": "Get up and run",
"author": "Johnny",
"tags": ["react", "javascript"]
}
]
我试图映射一个数组,结果是:(参见代码)
但我想得到这样的结果:
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: reactjavascript
或
我想同时正确地映射对象数组和“标记”数组
我该怎么做呢?做
tags={post.tags.map(xTag=>{return xTag;})}
相当于tags={post.tags}
。因此影响最终格式的相关代码在post组件中。也可以做tags.join(',)
或tags.map(t=>'.\t].join(“”)
您可以为标记创建单独的组件并设置其样式。
然后重写这一行:
tags={post.tags.map(xTag => {
return <Tag>{xTag}</Tag>; // or <Tag content={xTag} />
})}
tags={post.tags.map(xTag=>{
返回{xTag};//或
})}
如果要将标签数组转换为字符串,根据所需格式,有几个选项:
使用简单的联接,格式设置受到限制:(您可以传入将附加在每个条目后面的字符,例如.join(“”)
仅用于空格)
使用reduce
功能,您可以进一步控制字符串的格式:
post.tags.reduce((string, tag) => string += `${tag} `, '')
要更改格式,只需编辑附加的字符串${tag}
Tags: ["react", "javascript"] (it was the worst version :)(its fixed ;) ) )
tags={post.tags.map(xTag => {
return <Tag>{xTag}</Tag>; // or <Tag content={xTag} />
})}
post.tags.join() // Returns 'react,javascript'
post.tags.reduce((string, tag) => string += `${tag} `, '')