如何确保 Next.js router.query 不是未定义的?

Sha*_*oon 2 reactjs next.js

我正在使用next.jsimport { useRouter } from 'next/router'.

但是在初始加载时,router.query.idundefined. 它很快就会填满,但初始负载是一个杀手。

我试图弄清楚如何做到这一点,并尝试:

export async function getStaticProps({ params }) {
  // params contains the post `id`.
  // If the route is like /posts/1, then params.id is 1
  // const res = await fetch(`https://.../posts/${params.id}`)
  // const post = await res.json()
  console.log(params)
  // Pass post data to the page via props
  return { props: { params } }
}
Run Code Online (Sandbox Code Playgroud)

但这会返回一个错误:

Error: getStaticPaths is required for dynamic SSG pages and is missing for '/app/d/[id]'.
Run Code Online (Sandbox Code Playgroud)

我不能使用getStaticPaths,因为它[id]是可变的,可以是任意数量的东西。

那么处理这个问题的最佳方法是什么?

Pet*_*ter 6

我会像这样做 smt(没有 staticProps):

function Page(props) {
  const router = useRouter();
  const { query = {} } = router || {};
  const { id = 0 } = query || {};
  
  useEffect(()=> {
    if(id) {
      (async ()=> {
        const res = await fetch(`https://.../posts/${id}`)
        const post = await res.json();
      })();
    }
  }, [id]);

}
Run Code Online (Sandbox Code Playgroud)

这就是官方文档。说:

// You also have to define a Post component in the same file (pages/posts/[id].js)
function Post({ post }) {
  const router = useRouter()

  // If the page is not yet generated, this will be displayed
  // initially until getStaticProps() finishes running
  if (router.isFallback) {
    return <div>Loading...</div>
  }

  return <h1>Posts are here</h1>;
}

// This also gets called at build time
export async function getStaticProps({ params }) {
  // params contains the post `id`.
  // If the route is like /posts/1, then params.id is 1
  const res = await fetch(`https://.../posts/${params.id}`)
  const post = await res.json()

  // Pass post data to the page via props
  return { props: { post } }
}
Run Code Online (Sandbox Code Playgroud)

更新:

经过一番研究,找到了这个解决方案staticProps

export default function Post({ post }) {
  return <h1>Post is here</h1>;
}


export async function getStaticPaths() {
  return {
    paths: [
      { params: { id: '*' } }
    ],
    fallback: true
  };
}
    
export async function getStaticProps(context) {

  const res = await fetch(`https://api.icndb.com/jokes/random/${context.params.id}`);
  const post = await res.json()
  return { props: { post } }
}
Run Code Online (Sandbox Code Playgroud)