学习
静态路由
- 在文件夹命名文件名以
<dirname/filenme>
开始,即可通过你定义的文件夹的名称访问路由,如果该文件夹下的文件名是index
,则直接访问该文件夹的名称即可 例如: pages/about/me
对应是路由是 `http://localhost:3000/about/mepages/about/index
对应是路由是 `http://localhost:3000/about
动态路由
TIP 路径必须是字符串!!!
- 文件名以
[<filename>]
开始 - 使用
getStaticPaths
获取动态路由的路径,只能在SSG
中的getStaticProps
获取- 获取API接口中的所有的路径,并返回
params
对象中包含该路径, - 返回该路径以及配置项
- 获取API接口中的所有的路径,并返回
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>
</>
}
静态渲染
无数据渲染
不使用外部的数据
有数据渲染
-
使用
getStaticProps
获取外部的数据,并使用export
导出,该函数还必须是异步函数
例子:export async function getStaticProps(){
//code
} -
将获取的数据进行导出给其他组件渲染 例子:
export async function getStaticProps(){
const res = await fetch(uri,{})
const result = await res.json()
return {
props: {
result
}
}
} -
渲染组件接收
getStaticProps
传递的props
进行渲染
例子:
export default function About (props: { result: Array<List> }) {
const { result } = props
return (<>
result.map(() => {
// ..code
})
</>)
}