在 Next JS 中找不到自定义 [slug] 时重定向到 404

Redirect to 404 when custom [slug] is not found in 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>
    )
}

节点看起来像这样

export const nodes = [
{
    id: 'Test1'
}, {
    id: 'Test2'
}, {
    id: 'Test3'
}]

那么,如果我的 [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} />
    }
  }

谁能帮我解决这个问题。谢谢

您可以轻松定义状态并根据状态渲染您的组件。

import Error from "next/error";

// inside functional component
 const [errorCode , setErrorCode] = useState(0);
 const router = useRouter():
 
 useEffect(() => {
  const location =  router.query.location
  const search = nodes.filter(item => item.id === location ):
  if(search.length === 0){
    setErrorCode(404)
  }
 },[])
 
 if (errorCode == 404) {
   return (
      <Error statusCode={errorCode} title="page Not Found" />
   </>
   );
}
return (
  <Layout>
         ...My website...
    </Layout>
)

我希望您使用 getStaticProps & getStaticPaths 来解决这个问题。您可以使用 getSetaticProps 来获取静态道具。并定义哪些路径有效,您可以使用 getStaticPaths 并从节点变量加载路径。如果路径不存在,您可以简单地 return 404 错误而不是 props

请参考Next.js的官方文档了解更多getStaticProps & getStaticPaths