【问题标题】:Why would withRouter router.query be empty on first render in NextJS?为什么在 NextJS 中首次渲染时 withRouter router.query 为空?
【发布时间】:2019-12-19 05:39:25
【问题描述】:

当我调用 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)

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

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

为什么查询清楚地识别 asPath 却是空的?

【问题讨论】:

    标签: reactjs next.js


    【解决方案1】:

    这可能与Automatic Static Optimization 有关

    Next.js documentation 说:

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

    【讨论】:

      【解决方案2】:

      这是来自 React Router 的 withRouter 吗?

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

      【讨论】:

        猜你喜欢
        • 2021-04-22
        • 2022-10-02
        • 2020-03-08
        • 2022-01-23
        • 2021-07-27
        • 2022-01-20
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多