Next JS Custom Server app.render 不将查询传递给组件

Next JS Custom Server app.render do not pass query to a component

我试图通过 userDataapp.render,但是虽然 服务器端呈现 router.query 是空的,但我已经通过了userData!是NextJS的bug,还是我做错了什么?

app.js:

const { createServer } = require('http')
const { parse } = require('url')
const next = require('next')

const dev = process.env.NODE_ENV !== 'production'
const app = next({ dev })
const handle = app.getRequestHandler()

app.prepare().then(() => {
  createServer((req, res) => {

    const parsedUrl = parse(req.url, true)
    const { pathname, query } = parsedUrl

    if (pathname === '/index') {
      app.render(req, res, '/index', {
        userData: {
          id: 1,
          name: 'admin'
        }
      })
    } else {
      handle(req, res, parsedUrl)
    }
  }).listen(3333, err => {
    if (err) throw err
    console.log('> Ready on http://localhost:3000')
  })
})

pages/index.js:

import { useRouter } from 'next/router'

export default () => {
    const router = useRouter();
    const { query } = router;

    return (
        <div>
            Query: {JSON.stringify(query)}
        </div>
    );
};

我觉得很简单,就是在app.render之前加一条return语句,防止后面的代码执行。

if (pathname === '/index') {
  return app.render(req, res, '/index', {
    userData: {
      id: 1,
      name: 'admin'
    }
  })
} else {
  handle(req, res, parsedUrl)
}

If getInitialProps is absent, Next.js will statically optimize your page automatically by prerendering it to static HTML. During prerendering, the router's query object will be empty since we do not have query information to provide during this phase. Any query values will be populated client side after hydration.

您可以使用 getInitialProps 访问您的查询。
useRouter:

import { useRouter } from 'next/router'
const Index = () => {
  const router = useRouter();
  const { query } = router;

  return (
      <div>
          Query: {JSON.stringify(query)}
      </div>
  );
};

Index.getInitialProps = async () => {
  return {};
};
export default Index

带有 class 组件:

import React from 'react'

class Index extends React.Component {
      static async getInitialProps (context) {
        let query  = context.query;
        return {query}
      }

      render() {
        let {query} = this.props
        return (
          <div>
              Query: {JSON.stringify(query)}
          </div>
      );
      }
    }
export default Index  

或者,如果您更喜欢功能组件:

const Index = (props) => (
  <div>
    Query: {JSON.stringify(props.query)}
  </div>
)

Index.getInitialProps = async ( context ) => {
  let query  = context.query;
  return {query}
}

export default Index  

请注意,这显然适用于 /index 但不适用于 /