Skip to main content

学习

静态路由

  1. 在文件夹命名文件名以<dirname/filenme>开始,即可通过你定义的文件夹的名称访问路由,如果该文件夹下的文件名是index,则直接访问该文件夹的名称即可 例如:
  2. pages/about/me 对应是路由是 `http://localhost:3000/about/me
  3. pages/about/index 对应是路由是 `http://localhost:3000/about

动态路由

TIP 路径必须是字符串!!!

  1. 文件名以[<filename>] 开始
  2. 使用getStaticPaths获取动态路由的路径,只能在SSG中的getStaticProps获取
    1. 获取API接口中的所有的路径,并返回params对象中包含该路径,
    2. 返回该路径以及配置项
  3. getStaticProps获取getStaticPaths

示例:

export async function getStaticPaths () {
// 获取该接口的所有数据
const res = await fetch('https://jsonplaceholder.typicode.com/posts')
const result = await res.json()

console.log(result)

// 只获取该接口的路径, 该接口是以id区分
const paths = result.map((path: { id: string | number }) => {
return {
params: {
id: path.id.toString(), // id必须是字符串类型!
},
}
})

// 返回路径以及配置项
return {
paths,
fallback: false, // 完全匹配,其他路由是404
}
}

export async function getStaticProps (paths: { params: { id: string } }) {
// 接收路径
const { params } = paths
// 获取API的某一个路径的数据 ,由id决定
const res = await fetch(`https://jsonplaceholder.typicode.com/posts/${ params.id }`)
const result = await res.json()

// 返回接收到的数据
return {
props: { result },
}
}

// 渲染数据
export default function Posts (props: { result: { id: string, title: string, body: string } }) {
const { result } = props

return <>

<figure key={ result.id }>
<figcaption>
<p>{ result.title }</p>
<p>{ result.body }</p>
</figcaption>
</figure>
</>
}

静态渲染

无数据渲染

不使用外部的数据

有数据渲染

  1. 使用getStaticProps获取外部的数据,并使用export导出,该函数还必须是异步函数 例子:

    export async function getStaticProps(){
    //code
    }
  2. 将获取的数据进行导出给其他组件渲染 例子:

    export async function getStaticProps(){
    const res = await fetch(uri,{})
    const result = await res.json()

    return {
    props: {
    result
    }
    }
    }
  3. 渲染组件接收getStaticProps传递的props进行渲染

例子:

export default function About (props: { result: Array<List> }) {
const { result } = props

return (<>
result.map(() => {
// ..code
})
</>)
}