繁体   English   中英

为什么我在 getInitialProps 中使用 params 在 Next.js 中构建时它们是未定义的

[英]Why I use params in getInitialProps they are undefined when build in Next.js

我在 Next.js 中有这个问题。 我在getInitialProps调用 API 并将params传递给我的组件,然后当我在 mu 项目中使用它时它可以工作。 但是当我想构建它时,它给我的错误是paramsundefined

这就是我调用 API 并将其传递给组件的方式:

import BlogItem from './blogItem'
import axios from 'axios'
import { withRouter } from 'next/router'
import { APIURL, replaceAll } from '../../../components/config'
const Post = (props) => {
  return (

    <BlogItem
      services ={props.services }

    />

  )
}

Post.getInitialProps = async ({ query }) => {
  const id = query.id
  const urlTitle = encodeURI(query.title)
  const services  = null;

  try {
    const response = await axios.get(`${APIURL}getservice`);
    services = response.data.response.posts;
  } catch (err) {
    console.error(err)
  }

  return {
services 
  }
}

export default withRouter(Post)

您似乎将服务定义为包含nullconst 整个代码看起来不错。 尝试更改 const 以让:

Post.getInitialProps = async ({ query }) => {
  const id = query.id
  const urlTitle = encodeURI(query.title)
  let services  = null; //this line

  try {
    const response = await axios.get(`${APIURL}getservice`);
    services = response.data.response.posts;
  } catch (err) {
    console.error(err)
  }

  console.log(services) //you should have the data right here

  return {services}
}

例子:看看这个例子。 运行它并导航到/about页面:

编辑落风-d9ych

您需要确保将您的 url 参数传递到服务器上的查询字符串中,在您的情况下,如下所示:

server.get('/page/:uid/:id', (req, res) => {
  const mergedQuery = Object.assign({}, req.query, req.params)
  return app.render(req, res, '/page', mergedQuery);
})

然后您的 getInitialProps 可以直接从查询中获取它们,而不管它在哪里加载。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM