使用 next.js 以 Sanity 访问 Post 数组中的数组

Access to an Array inside a Post Array with Sanity using next.js

我在尝试访问类别数组中的 Post 数组时遇到问题。所以如果我 console.log 我看到的数据是这样的:

{
  posts: [
    {
      _createdAt: '2021-10-23T05:02:26Z',
      _type: 'post',
      _updatedAt: '2021-10-23T23:28:09Z',
      body: [Array],
      categories: [Array], <<<<-- this is the one I need to access
      mainImage: [Object],
      publishedAt: '2021-10-23T18:30:00.000Z',
      slug: [Object],
      title: 'Post Name title goes here'
    }
   .
   .
   .
  ]
}

我需要访问我的 Post 数组中的类别数组,但我很难访问它。我目前尝试过这样的事情:

 <div className="grid grid-cols-1 lg:grid-cols-3 gap-4">
  {posts.map(
    ({
      _id,
      title = "",
      slug = "",
      _createdAt = "",
      mainImage = "",
      categories = "",
    }) =>
      slug && (
        <div className="shadow-lg rounded-lg bg-white pb-5" key={_id}>
          <div className="px-6 py-4 text-left">
            <div className="flex flex-row mt-4 items-center">
              {categories && (
                <ul className="inline-flex my-3" style={{ listStyle: "none" }}>
                  {categories.map((category) => (
                    <li key={category}>
                      <span
                        className="mx-2 
                          items-center
                          justify-center
                          px-2
                          py-1
                          text-xs
                          font-bold"
                      >
                        {category}
                      </span>
                    </li>
                  ))}
                </ul>
              )}
            </div>
          </div>
        </div>
      )
  )}
</div>;

执行此操作时出现以下错误:

对象作为 React 子项无效(找到:具有键 {_key, _ref, _type} 的对象)。如果您打算渲染一组子项,请改用数组。

我什至试过这样做:

{posts.categories.map((category) => (
    <li key={category}>
      <span
        className="mx-2 
            items-center
            justify-center
            px-2
            py-1
            text-xs
            font-bold"
      >
        {category}
      </span>
    </li>
  ));
}

但还是没有运气。关于我做错了什么的任何想法?谢谢!

你想要数组的数组吗?

const arrayOfArrayOfCategories = posts.map(post => post.categories);

如果您想访问第一个 post 的类别:

const { categories } = posts[0];

总是最好拆分代码以使其更容易。我会为 Post 创建单独的组件,将 post 作为道具。然后导入到你需要的地方。

Post.js

function Post({ post }) {
  const { categories } = post;

  function renderCategories() {
    return categories.map((category) => {
      return <span>{category}</span>;
    });
  }
  return <div>{renderCategories()}</div>;
}

export default Post;

App.js

import Post from "./Post";

function App() {
  const posts = [
    {
      _createdAt: "2021-10-23T05:02:26Z",
      _type: "post",
      _updatedAt: "2021-10-23T23:28:09Z",
      body: [Array],
      categories: ["categoiry", "sfsdfd", "eosiefoise", "dseuhse"],
      mainImage: [Object],
      publishedAt: "2021-10-23T18:30:00.000Z",
      slug: [Object],
      title: "Post Name title goes here",
    },
    {
      _createdAt: "2021-10-23T05:02:26Z",
      _type: "post",
      _updatedAt: "2021-10-23T23:28:09Z",
      body: [Array],
      categories: ["categoiry", "sfsdfd", "eosiefoise", "dseuhse"],
      mainImage: [Object],
      publishedAt: "2021-10-23T18:30:00.000Z",
      slug: [Object],
      title: "Post Name title goes here",
    },
    {
      _createdAt: "2021-10-23T05:02:26Z",
      _type: "post",
      _updatedAt: "2021-10-23T23:28:09Z",
      body: [Array],
      categories: ["categoiry", "sfsdfd", "eosiefoise", "dseuhse"],
      mainImage: [Object],
      publishedAt: "2021-10-23T18:30:00.000Z",
      slug: [Object],
      title: "Post Name title goes here",
    },
  ];

  function renderPosts() {
    return posts.map((post) => {
      return <Post post={post} />;
    });
  }

  return <div>{renderPosts()}</div>;
}

从错误看来 categories 是一个引用数组。您需要解析 GROQ 查询中的引用(类似于 "categories": categories[]->),然后在您的前端,您需要使用每个 [=14] 的 properties =](在映射 categories 时创建)而不是整个对象本身。你会想像你所做的那样映射 categories,但在映射回调函数中你永远不会直接引用整个对象。

而不是:

{posts.categories.map((category) => (
    <li key={category}>
      <span>
        {category}
      </span>
    </li>
  ));
}

你会想做类似的事情(假设 text 属性 存在):

{posts.categories.map((category) => (
    <li key={category._id}>
      <span>
        {category.text}
      </span>
    </li>
  ));
}