基於檔案的 Next.js 頁面路由
今年下半年接了一個公司的對外專案,因此有 SEO 需求,不知道是不是靜茹給我的勇氣,讓我主動提出可以使用 Next.js 的 SSR 來架構新專案,總之就是且戰且走吧,從零開始一邊做一邊學。
useRouter hook
1// file: <root>/pages/clients/[id]/[projectId].js 2// visit: localhost:3000/clients/sean/project1 3 4import { useRouter } from 'next/router'; 5 6function SelectedClientProjectPage() { 7 const router = useRouter(); 8 9 console.log(router.pathname); // "clients/[id]/[projectId]" 10 console.log(router.query); // {projectId: "project1", id: "sean"} 11 12 // send a request to some backend server 13 // to fetch the piece of data with an id of router.query.projectId 14 15 return ( 16 <div> 17 <h1>The Project Page for a Specific Project for a Selected Client</h1> 18 </div> 19 ); 20} 21 22export default SelectedClientProjectPage; 23
Catch-All Routes
e.g. [...xxx].js
1// file: <root>/pages/blog/[...slug].js 2// visit: localhost:3000/blogs/2023/09 3 4import { useRouter } from 'next/router'; 5 6function BlogPostsPage() { 7 const router = useRouter(); 8 9 console.log(router.query); // {slug: ["2023", "09"]} 10 11 return ( 12 <div> 13 <h1>The Blog Posts</h1> 14 </div> 15 ); 16} 17 18export default BlogPostsPage; 19
Navigating To Dynamic Routes
1import Link from 'next/link'; 2 3function ClientsPage() { 4 const clients = [ 5 { id: 'sean', name: 'Sean' }, 6 { id: 'chi', name: 'Chi' }, 7 ]; 8 9 return ( 10 <div> 11 <h1>The Clients Page</h1> 12 <ul> 13 {clients.map((client) => ( 14 <li key={client.id}> 15 <Link href={`/clients/${client.id}`}>{client.name}</Link> 16 </li> 17 ))} 18 </ul> 19 </div> 20 ); 21} 22 23export default ClientsPage; 24
A Different Way Of Setting Link Hrefs
1<Link 2 href={{ 3 pathname: '/clients/[id]', 4 query: { id: client.id }, 5 }} 6> 7 {client.name} 8</Link> 9
Navigating Programmatically
1const router = useRouter(); 2 3router.push({ 4 pathname: '/clients/[id]/[projectId]', 5 query: { id: 'sean', projectId: 'project1' }, 6}); 7
Custom 404 Page
1// file: <root>/pages/404.js (Must) 2// visit: localhost:3000/something 3 4function NotFoundPage() { 5 return ( 6 <div> 7 <h1>Page not found!</h1> 8 </div> 9 ); 10} 11 12export default NotFoundPage; 13
Public folder
Files and folders stored outside of public/
are NOT made accessible by Next.js - visitors can NOT load files from there.