【问题标题】:Error: A required parameter (slug) was not provided as a string in getStaticPaths for /posts/[slug]错误:在 getStaticPaths 中没有为 /posts/[slug] 提供所需参数(slug)作为字符串
【发布时间】:2021-09-04 22:36:09
【问题描述】:

我的项目中有以下 [slug].js 文件:

import Head from "next/head";
import PostContent from "../../components/posts/post-detail/post-content";
import { getPostByName, getAllPosts } from "../../helpers/api-util";

function PostDetailPage(props) {
  const post = props.selectedPost;
  console.log(post);
  if (!post) {
    return (
      <div className="">
        <p>Loading...</p>
      </div>
    );
  }
  return <PostContent post={post.slug} />;
}


export async function getStaticProps(context) {
  const blogSlug = context.params.slug;
  const post = await getPostByName(blogSlug);
  return {
    props: {
      selectedPost: post,
    }, // will be passed to the page component as props
  };
}

export async function getStaticPaths() {
  const posts = await getAllPosts();
  const paths = posts.map(post => ({ params: { blogSlug: post.slug } }));

  return {
    paths: paths,
    fallback: "blocking",
  };
}

export default PostDetailPage;

这是我的文件结构:

我使用以下数据结构从 firebase 获取数据:

这个想法是,当我在“所有帖子”页面上单击我的帖子时,我会进入包含我所有帖子信息的 PostContent 组件。

一旦我尝试点击某个特定帖子,就会收到主题中提到的错误。

Slug 不是字符串,所以我不完全确定为什么会得到这个。

谢谢

【问题讨论】:

    标签: next.js


    【解决方案1】:

    您的返回blogSlug 键入getStaticPaths:

    const paths = posts.map(post => ({ params: { blogSlug: post.slug } }));
    

    但您的文件名为 [slug].js,您希望在 getStaticProps 中有一个 slug 键:

    const blogSlug = context.params.slug;
    

    应该是一致的,在这种情况下,它应该被命名为slug。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-10-05
      • 2021-12-12
      • 2021-08-26
      • 2021-07-23
      • 2021-03-25
      • 1970-01-01
      • 2019-06-21
      • 2021-11-07
      相关资源
      最近更新 更多