Tho*_*Byy 6 custom-error-pages next.js
我很惊讶我无论如何也找不到这个,但这是我的问题。我有一个 Next JS 站点,其路径/location/[location].js
为该页面看起来非常基本
import { nodes } from '../../components/data/nodes'
export default function Location() {
const router = useRouter()
useEffect(() => {
//Do various things
}, [])
return (
<Layout>
...My website...
</Layout>
)
}
Run Code Online (Sandbox Code Playgroud)
节点看起来像这样
export const nodes = [
{
id: 'Test1'
}, {
id: 'Test2'
}, {
id: 'Test3'
}]
Run Code Online (Sandbox Code Playgroud)
那么,如果我的 [location] slug 与任何节点 id 都不匹配,我该怎么说才能转到 404 页面呢?我尝试了一些简单的垃圾,但感觉不对并抛出控制台错误:
var counter = 1
for (var node of nodes) {
if (router.query.location == node.id) {
break
} else if (counter++ >= nodes.length) {
return <Error statusCode={404} />
}
}
Run Code Online (Sandbox Code Playgroud)
有人可以帮我解决这个问题吗?谢谢
我希望你使用getStaticProps&getStaticPaths来解决这个问题。您可以使用getStaticProps来获取静态道具。要定义哪些路径有效,您可以使用getStaticPaths和加载节点变量中的路径。如果路径不存在,您可以简单地返回 404 错误,而不是props
Next.js更多信息请参考官方文档getStaticProps&getStaticPaths
| 归档时间: |
|
| 查看次数: |
15796 次 |
| 最近记录: |