首页 > 解决方案 > 在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>

标签: jsonreactjs

解决方案


我想这就是你所追求的。

沙盒

<section className="col1">
  {Array.isArray(tags) ? (
    tags.map((tag) => (
      <span style={{ marginRight: "10px" }}>{tag}</span>
    ))
  ) : (
    <span>{tags}</span>
  )}
</section>

即使只有一个元素,您也可以使该代码更简单,让该tags字段始终是一个数组。


推荐阅读