0

我想在我的标题菜单“学习”中显示“最近的文章”,但由于我使用的是 NextJS,所以我不能在自定义组件中使用 getStaticProps。如何将 GraphQL 查询从文章页面传递到自定义组件?

谁能帮我举一个在页面上使用 getStaticProps 并将其传递给自定义组件的示例?

这是我的articles.jsx 文件的getStaticProps 部分,顶部有导入:

import {
  getPaginatedArticles,
  getPaginatedCases,
  getArticles,
  getRecentArticles,
} from "../utils/contentful";

export async function getStaticProps() {
  const articles = await getPaginatedArticles();
  const cases = await getPaginatedCases();
  const categories = await getArticles();
  const recentArticles = await getRecentArticles();

  return {
    props: {
      articles: articles.articleCollection.items,
      cases: cases.caseCollection.items,
      categories: categories.articleCollection.items,
      recentArticles: recentArticles.articleCollection.items,
    },
  };
}

这是来自上述导入的 recentArticles 查询:

export async function getRecentArticles() {
  const recentArticlesQuery = gql`
    {
      articleCollection(order: date_DESC, limit: 3) {
        items {
          title
          slug
          excerpt
          date
          contentfulMetadata {
            tags {
              name
              id
            }
          }
          featuredImage {
            title
            url
            width
            height
          }
          author {
            name
            photo {
              fileName
              url
              width
              height
            }
            title
            twitterProfile
            linkedInProfile
            slug
          }
        }
      }
    }
  `;
  return graphQLClient.request(recentArticlesQuery);
}

如开头所述,如果我在文章页面中使用它,它会起作用,但我想在我的标题中使用它。

这是我的标题自定义组件中的“学习”菜单的简化版本:

export default function Header() {
  return (
   <div>
     <h3>Recent Posts</h3>
       <ul>{recentPosts.map((post) => (
         <li
          key={post.id}>
            <a href={post.href}>
              {post.name}
            </a>
         </li>
         ))}
       </ul>
  </div>
 )                                 
}

如何从articles.jsx 文件中将数据引入我的自定义标头组件?

4

0 回答 0