为什么 withRouter router.query 在 NextJS 中第一次渲染时会是空的?

Dan*_*ein 12 reactjs next.js

当我调用 withRouter 时,我能够在数据第二次呈现时看到输出。

我的组件如下所示:

const Home = (props) => {
  console.log("all props", props)
  let { router } = props
  let { category, item } = router.query
  console.log("Cat", category)
  console.log("Item", item)
  return (
    <FirebaseContext.Provider value={new Firebase()}>
      <div>
        <Head>
          <title>Category</title>
        </Head>
        <Navigation />
        {/* <Item category={category} item={item} {...props} /> */}
      </div>
    </FirebaseContext.Provider>
  )
}

Home.getInitialProps = async (props) => {
  console.log(props)
    return { req, query }
}

export default compose(withRouter, withAuthentication)(Home)
Run Code Online (Sandbox Code Playgroud)

如果你看控制台,第一个渲染看起来像:

asPath: "/c/cigars/1231"
back: ƒ ()
beforePopState: ƒ ()
events: {on: ƒ, off: ƒ, emit: ƒ}
pathname: "/c/[category]/[item]"
prefetch: ƒ ()
push: ƒ ()
query: {}
Run Code Online (Sandbox Code Playgroud)

为什么查询是空的,即使它清楚地识别了 asPath?

Ste*_*ric 23

这可能与自动静态优化

Next.js 文档说有关:

通过自动静态优化进行静态优化的页面将在不提供路由参数的情况下进行水合,即,query将是一个空对象 ( {})。


Jon*_*win 2

是 React Router 中的 withRouter 吗?

如果是,则不会添加查询道具 - 它将添加名为:位置、历史记录和匹配的道具