Jua*_*dez 6 static-site reactjs server-side-rendering next.js ssg
"Error: getStaticPaths is required for dynamic SSG pages and is missing for 'xxx'"当我尝试在 NextJS 中创建我的页面时出现此错误。
我不想在构建时生成任何静态页面。那么为什么我需要创建一个'getStaticPaths'函数呢?
Jua*_*dez 17
如果您正在创建一个动态页面,例如:product/[slug].tsx那么即使您不想在构建时创建任何页面,您也需要创建一个getStaticPaths方法来设置fallback属性并让 NextJS 知道当您尝试获取的页面没有时该怎么做不存在。
export const getStaticPaths: GetStaticPaths<{ slug: string }> = async () => {
return {
paths: [], //indicates that no page needs be created at build time
fallback: 'blocking' //indicates the type of fallback
}
}
Run Code Online (Sandbox Code Playgroud)
getStaticPaths 主要做两件事:
指示应在构建时创建哪些路径(返回paths数组)
指示当某个页面(例如:“product/myProduct123”在 NextJS 缓存中不存在时要执行的操作(返回fallback类型)
为了渲染动态路线,请 getServerSideProps()使用getStaticProps()
例如:
export async function getServerSideProps({
locale,
}: GetServerSidePropsContext): Promise<GetServerSidePropsResult<Record<string, unknown>>> {
return {
props: {
...(await serverSideTranslations(locale || 'de', ['common', 'employees'], nextI18nextConfig)),
},
}
}
Run Code Online (Sandbox Code Playgroud)
动态路由 Next Js
页面/用户/[id].js
import React from 'react'
const User = ({ user }) => {
return (
<div className="row">
<div className="col-md-6 offset-md-3">
<div className="card">
<div className="card-body text-center">
<h3>{user.name}</h3>
<p>Email: {user.email} </p>
</div>
</div>
</div>
</div>
)
}
export async function getStaticPaths() {
const res = await fetch('https://jsonplaceholder.typicode.com/users')
const users = await res.json()
const paths = users.map((user) => ({
params: { id: user.id.toString() },
}))
return { paths, fallback: false }
}
export async function getStaticProps({ params }) {
const res = await fetch(`https://jsonplaceholder.typicode.com/users/${params.id}`)
const user = await res.json()
return { props: { user } }
}
export default User
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
8063 次 |
| 最近记录: |