最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Why would a query param be undefined in NextJS? - Stack Overflow

programmeradmin5浏览0评论

I'm calling a page withRouter(Page) and expect the variable for the page (the page is called [category].js) to be present on initial page load. Query itself is there, the key is there, but the value is 'undefined.' There seem to be a few calls to getInitialProps on the server side with 2/3 being undefined.

The react ponent has a constructor, etc. it's not a functional ponent.

This is my current getInitialProps:

Category.getInitialProps = async ({ req, query }) => {
  let authUser = req && req.session && req.session.authUser
  let categoryData = {}
  let categoryItemData = {}
  let category = query.category
  if(category){
    let res = await fetch(url1,
    {
        method: 'POST',
        credentials: 'include',
    })
    categoryData = await res.json();
    let categoryItemsRes =  await fetch(url2, 
        {
            method: 'POST',
            credentials: 'include',
        })
    categoryItemData = await categoryItemsRes.json();
  }

  return { query, authUser, categoryData, categoryItemData }
}

I'm calling a page withRouter(Page) and expect the variable for the page (the page is called [category].js) to be present on initial page load. Query itself is there, the key is there, but the value is 'undefined.' There seem to be a few calls to getInitialProps on the server side with 2/3 being undefined.

The react ponent has a constructor, etc. it's not a functional ponent.

This is my current getInitialProps:

Category.getInitialProps = async ({ req, query }) => {
  let authUser = req && req.session && req.session.authUser
  let categoryData = {}
  let categoryItemData = {}
  let category = query.category
  if(category){
    let res = await fetch(url1,
    {
        method: 'POST',
        credentials: 'include',
    })
    categoryData = await res.json();
    let categoryItemsRes =  await fetch(url2, 
        {
            method: 'POST',
            credentials: 'include',
        })
    categoryItemData = await categoryItemsRes.json();
  }

  return { query, authUser, categoryData, categoryItemData }
}
Share asked Aug 13, 2019 at 23:15 ThingamajigThingamajig 4,4678 gold badges36 silver badges66 bronze badges 1
  • 1 Appears getInitialProps is being called twice, not sure why that would be the case. Once with the data, once without. – Thingamajig Commented Aug 13, 2019 at 23:20
Add a ment  | 

2 Answers 2

Reset to default 5

This might be redundant at this point, but I ran into this as well and found the docs explain this here

During prerendering, the router's query object will be empty since we do not have query information to provide during this phase. After hydration, Next.js will trigger an update to your application to provide the route parameters in the query object.

You might try this instead:

export async function getServerSideProps(ctx) {
  const { id } = ctx.query;
  return {
    props: {
      id,
    },
  };
}

This way it gets the query params when rendering server side, so they're instantly available.

For others who use express custom server, to fix the undefined params, we have to set the dynamic route at server.js as follow:

# server.js
...

app.prepare().then(() => {
  const server = express();
  ....

  server.get('/product/:category', (req, res) => {
    const { category } = req.params;
    return app.render(req, res, `/product/${category}`, req.query)
  })
  
  ...
}

And then, as Valentijn answers, we can get the category params.

# pages/product/[category].js
....

export async function getServerSideProps(ctx) {
  const {category} = ctx.params;
  return {
    props: {
      category
    },
  };
};

...

The key is dynamic path /product/${category}. Don't use /product/:category

发布评论

评论列表(0)

  1. 暂无评论