json - 在reactjs中的不同span标签中分离并显示多个json值
问题描述
我有一个用 json 数据json
调用的对象。blogData
在 json obj 中,tags
键可能有多个标签值。我想在span
使用 map 函数进行迭代时在标签中分别显示标签值。
现在多个标签显示在一个跨度标签中(请参见下文)我该如何解决这个问题?
const blogData = [
{
"id" : 1,
"title":"Cypress tests",
"images":"/images/image1.jpg",
"description": "Add the E2E cypress UI tests",
"tags": "cypress"
},
{
"id" : 2,
"title":"Jmeter tests",
"images":"/images/image2.jpg",
"description": "Performance test using Jmeter tool",
"tags": ["jmeter", "performance"]
},
{
"id" : 3,
"title":"Basic Unix commands",
"images":"/images/image3.jpg",
"description": "Learn basic unix commands in git bash",
"tags": "unix"
},
{
"id" : 4,
"title":"Postman",
"images":"/images/image4.jpg",
"description": "Api testing using postman",
"tags": ["postman", "api"]
},
]
Home.js
const [searchResults, setSearchResults] = useState([]);
<div className="container">
{
searchResults.map(({ id, title, images, description, tags }) => (
<div key={id} className="column-center">
{/* <img className="blogImage" key={images} src={images} alt="image"></img> */}
<div className="blogtitle">
<span key={title}>{title}</span>
</div>
<section>
<p className="blogdescription" key={description}>{description}</p>
</section>
<section className="col1">
<span key={tags}>{tags}</span>
</section>
<section className="col2">
<a>Read more {'>'}{'>'}</a>
</section>
</div>
))
}
</div>
解决方案
我想这就是你所追求的。
<section className="col1">
{Array.isArray(tags) ? (
tags.map((tag) => (
<span style={{ marginRight: "10px" }}>{tag}</span>
))
) : (
<span>{tags}</span>
)}
</section>
即使只有一个元素,您也可以使该代码更简单,让该tags
字段始终是一个数组。
推荐阅读
- vue.js - 生产期间的Vue CLI websocket错误
- r - 如何从 .SD 语法转到带有 data.table 的集合语法?
- flutter - 在颤振上播放视频
- angular - ngrx 将对象添加到相同的 id
- django-rest-framework - DRF Viewset - 如果数据存在,如何创建或更新
- c - 函数不打印 C 文件中的 while 行
- javascript - 如果项目在 s3 中不存在,AWS SDK 崩溃节点应用程序
- woocommerce - 风格化 woocommerce 价格小数点:问题
- python - 将嵌套字典解析为数据框
- delphi - 解决 Indy 中的“SSL 握手错误”