Next.js- 基础

一. Next.js 是围绕着 页面(pages) 的概念构造的。

  一个页面(page)就是一个从 pages 目录下的 .js.jsx.ts 或 .tsx 文件导出的 React 组件

 页面(page) 根据其文件名与路由关联。例如,pages/about.js 被映射到 /about

  甚至可以在文件名中添加动态路由参数。

二. 具有动态路由的页面

创建了一个命名为 pages/posts/[id].js 的文件,那么就可以通过 posts/1posts/2 等类似的路径进行访问。

三. 预渲染

静态生成(Static Generation) 和 服务器端渲染(Server-side Rendering)

Next.js 允许你为每个页面 选择 预渲染的方式。

四. 页面中获取数据

  1. 页面 内容 取决于外部数据:使用 getStaticProps
  2. 页面 paths(路径) 取决于外部数据:使用 getStaticPaths (通常还要同时使用 getStaticProps)。
    // TODO: 需要获取 `posts`(通过调用 API )
    //       在此页面被预渲染之前
    function Blog({ posts }) {
      return (
        <ul>
          {posts.map((post) => (
            <li>{post.title}</li>
          ))}
        </ul>
      )
    }
    
    // 此函数在构建时被调用
    export async function getStaticProps() {
      // 调用外部 API 获取博文列表
      const res = await fetch('https://.../posts')
      const posts = await res.json()
    
      // 通过返回 { props: { posts } } 对象,Blog 组件
      // 在构建时将接收到 `posts` 参数
      return {
        props: {
          posts,
        },
      }
    }
    export default Blog
    // 此函数在构建时被调用
    export async function getStaticPaths() {
      // 调用外部 API 获取博文列表
      const res = await fetch('https://.../posts')
      const posts = await res.json()
    
      // 据博文列表生成所有需要预渲染的路径
      const paths = posts.map((post) => ({
        params: { id: post.id },
      }))
    
      // We'll pre-render only these paths at build time.
      // { fallback: false } means other routes should 404.
      return { paths, fallback: false }
    }
    
    // 在构建时也会被调用
    export async function getStaticProps({ params }) {
      // params 包含此片博文的 `id` 信息。
      // 如果路由是 /posts/1,那么 params.id 就是 1
      const res = await fetch(`https://.../posts/${params.id}`)
      const post = await res.json()
    
      // 通过 props 参数向页面传递博文的数据
      return { props: { post } }
    }
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值