在 Sanity Io React 中循环遍历数组

Looping through array within Sanity Io React

我正在使用 react with sanity io 创建投资组合页面。我想根据我在项目上有多少标签来创建一个无序列表。一个项目由标题、图片、描述和标签组成(这只是一个数组)。

我试过的是:

{project.tags.map(type => {
    return (
       <li>{type.type.name}</li>
       )
})}

而且我不断收到错误消息:“TypeError:project.forEach 不是函数”。如果我只是渲染

{project.tags}

显示了所有标签,但我无法设置它们的样式,因此需要将它们放入列表中。

有谁知道如何做到这一点?

import React, { useEffect, useState} from "react";
import sanityClient from "../client.js";
import '../index.css';


export default function Project() {
    const [projectData, setProjectData] = useState(null);

    useEffect(() => {
        sanityClient.fetch(`*[_type == "project"] | order(index) {
            title,
            mainImage{
                asset->{
                    _id,
                    url
                },
            },
            description,
            projectType,
            link,
            tags
        }`).then((data) => setProjectData(data)).catch(console.error);
    }, []);

    return (
        <div className="antialiased text-gray-800 bg-gray-400">
            <div className="container relative flex flex-col px-6 mx-auto space-y-8">
                <div className="absolute inset-0 z-0 w-2 h-full bg-white shadow-md left-38 md:mx-auto md:right-0 md:left-0"></div>
                {projectData && projectData.map((project, index)=> (
                <div className="relative z-10 p-10 ">
                    <img src={project.mainImage.asset.url} alt={project.mainImage.alt} className="timeline-img" />
                    <div className={`${index % 2 === 0 ? "timeline-container-left timeline-container" : "timeline-container" }`} >
                        <p className="font-bold uppercase">{project.title}</p>
                        <div className={`${index % 2 === 0 ? "timeline-pointer-left timeline-pointer" : "timeline-pointer" }`} aria-hidden="true"></div>
                        <div className="p-6 bg-white rounded-md shadow-md sm:p-2">
                            <p className="pt-1">{project.description}</p>
                        </div>
                        

                    </div>
                </div>  
                ))}
            </div>
        </div>
    )
}

{project.tags.map( type => (

  • {type}
  • ))} 是答案。