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

reactjs React.js

西里飞云

2020-03-24

当我用Router调用时,我能够在第二次渲染数据时看到输出。

我的组件看起来像这样:

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,查询还是为空?

第3565篇《为什么在NextJS中第一次渲染时withRouter router.query为空?》来自Winter(https://github.com/aiyld/aiyld.github.io)的站点

1个回答
神奇米亚神乐 2020.03.24

那是来自React Router的withRouter吗?

If it is it will not add a query prop - it will add props called: location, history and match

问题类别

JavaScript Ckeditor Python Webpack TypeScript Vue.js React.js ExpressJS KoaJS CSS Node.js HTML Django 单元测试 PHP Asp.net jQuery Bootstrap IOS Android