【问题标题】:Dynamic Content not loading in NextJs Dynamic PagesNextJs 动态页面中未加载动态内容
【发布时间】:2021-08-28 11:24:02
【问题描述】:

目前,我的 Strapi CMS 中有一个博客集合类型,其中包含一个 ID 和标题数据字段。我在前端使用 NextJs 为每个博客页面动态加载博客内容。但是当我的动态页面加载时,我的内容没有加载。

存储个人博客的页面:

{posts &&
        posts.map((item, idx) => (
          <Link href={`/BlogPage/${item.id}`}>
            <div>
              <img src={`http://localhost:1337${item.Thumbnail.url}`}/>
            </div>
          </Link>

然后在我的 BlogPage 目录中我有一个文件 [id].js:

export default function name({blog}) {
    return (
      <>     
      <div>
        {blog.Title}
      </div>
</>
)}
// Tell nextjs how many pages are there
export async function getStaticPaths() {
  const res = await fetch("http://localhost:1337/blogs");
  const posts = await res.json();

  const paths = posts.map((blog) => ({
    params: { id: blog.id.toString() },
  }));

  return {
    paths,
    fallback: false,
  };
}

// Get data for each individual page
export async function getStaticProps({ params }) {
  const { id } = params;

  const res = await fetch(`http://localhost:1337/blogs?id=${id}`);
  const data = await res.json();
  const posts = data[0];

  return {
    props: { posts },
  };
}

这会将我带到这个 URL http://localhost:3000/BlogPage/1 并给我一个错误

TypeError: 无法读取未定义的属性“标题”

【问题讨论】:

    标签: next.js strapi


    【解决方案1】:

    尝试出name函数的getStaticProps和getStaticPaths

    
    export async function getStaticPaths() {
      const res = await fetch("http://localhost:1337/blogs");
      const posts = await res.json();
    
      const paths = posts.map((blog) => ({
        params: { id: blog.id.toString() },
      }));
    
      return {
        paths,
        fallback: false,
      };
    }
    
    
    export async function getStaticProps({ params }) {
      const { id } = params;
    
      const res = await fetch(`http://localhost:1337/blogs?id=${id}`);
      const data = await res.json();
      const posts = data[0];
    
      return {
        props: { posts },
      };
    }
    
    export default function name({posts }) { // change this line
        return (
          <>     
          <div>
            {posts.Title} // change this line // Are you sure is it Title? not title? if it is with lowercase, it will return null
          </div>
         </>
        )
    }
    
    

    【讨论】:

    • 哦,是的帖子有效。谢谢。但我仍然在使用 .map(blog) 那么为什么要使用 posts.title?
    • 对不起,我不明白你到底是什么意思,如果你在谈论为什么从(博客)更改为(帖子),只是你作为道具传递给页面组件的 getStaticProps。 nextjs.org/docs/basic-features/data-fetching#example
    猜你喜欢
    • 2021-10-01
    • 2017-03-05
    • 2012-10-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-08-03
    相关资源
    最近更新 更多