此问题常见于运行Next.js应用于AWS Amplify时。原因是在部署应用程序时,可能会出现缺少构建文件或未正确设置路由的情况,导致应用程序无法正确路由至ISR页面。
为了解决这个问题,可以使用下列步骤:
export async function getStaticProps(context) { return { props: {}, // will be passed to the page component as props revalidate: 60, //time to re-generate static page } }
npm run build
version: 1 frontend: phases: preBuild: commands: - npm install build: commands: - npm run build artifacts: baseDirectory: .next files: - '/*' cache: paths: - node_modules//*
在‘app.js’中:
import { useRouter } from 'next/router' import { useEffect } from 'react'
export default function App({ Component, pageProps }) { const router = useRouter()
useEffect(() => { const handleRouteChange = url => { // check for the current route if (url.includes('/products/') || url.includes('/about/')) { router.prefetch(url) } }
// Subscribe to router events
router.events.on('routeChangeStart', handleRouteChange)
// Unsubscribe from router events when component is unmounted
return () => {
router.events.off('routeChangeStart', handleRouteChange)
}
}, [])
return
在‘[slug].js’页面中:
export const getStaticPaths = async () => { const paths = [ { params: { slug: 'products/a' } }, { params: { slug: 'products/b' } }, { params: { slug: 'products/c' } }, ] return { paths, fallback: true } }
export const getStaticProps = async ({ params }) => {
const slug = params.slug
const title = Product ${slug.split('/')[1]}
return {
props: {
title,
},
revalidate: 60 * 60 * 24, // 24 Hours
}
}
export default function Product({ title }) { return
通过遵循以上步骤,您应该能够消除此问题并成功在AWS Amplify上部署NextJS应用程序。