为什么我无法在 ```getStaticProps``` 中获取查询参数?

Ali*_*h r 5 javascript reactjs next.js

我会让它变得简单:

关联: http://localhost:3000/product/bioCloths?activeCategory=medium&id=0

文件路径:pages/product/[product].js.

预期的: product: "bioCloths, activeCategory: "medium", id: "0"

使用getStaticProps[product].js

const ProductDetails = (props) => {
  console.log("initial props", props);

  return <div>product details...</div>
};

export default ProductDetails;

export async function getStaticProps(context) {

  return {
    props: {
     context: context
    },
  };
}

export async function getStaticPaths() {
  return {
    paths: [{ params: { product: "1" } }, { params: { product: "2" } }],
    fallback: true,
  };
}
Run Code Online (Sandbox Code Playgroud)

Props返回:context: params: product: "bioCloths",不包括查询参数。

现在,如果我使用已弃用的getInitialProps代替:

ProductDetails.getInitialProps = (context) => {
  const activeCategory = context.query.activeCategory;
  const id = context.query.id;
  const product = context.query.product;

  return {
    activeCategory: activeCategory,
    id: id,
    product: product,
  };
};
Run Code Online (Sandbox Code Playgroud)

道具日志 activeCategory: "medium" id: "0" product: "bioCloths"

我需要获得所有这些道具,以便我可以fetch在客户端安装之前获取数据。

我知道getInitialProps现在已弃用,但它有效。为什么不getStaticProps工作,我应该用它代替serverSideProps吗?

这是一个电子商务,我无法设置getStaticPaths数百种可能性来与之合作,getStaticProps所以我想在这种情况下我应该使用getInitialProps or getServerSideProps?

PS -getServerSideProps给我一个错误,指出它只会接受.json文件。

Ali*_*h r 9

根据其中一位维护者的说法,Nextjs这是对任何学习此框架的人的答复:

getStaticProps在构建时生成页面。无法知道访问者在构建时可以使用的自定义查询参数。

getInitialProps并且getServerSideProps可以知道所有可能的查询参数,因为页面是在运行时生成的,无论何时收到新请求。

您可以在此处了解有关上述内容的更多信息。

这个讨论可以在Github上阅读


Sus*_*ary 7

如果您的页面使用动态路由,params请包含路由参数。例如,如果页面名称是[id].js,则将params如下所示:

\n
{ id: /* something */ }\n
Run Code Online (Sandbox Code Playgroud)\n

您可以使用上下文参数从或函数内部获取URL 参数。\nHere\xe2\x80\x99s 是一个示例:getStaticPropsgetServerSidePropsgetStaticProps

\n
// pages/[id].js\n\nexport async function getStaticProps(context) {\n    const { params } = context;\n    const id = params.id;\n\n    const data = /* Fetching data with the id */\n\n    return {\n        props: data,\n    }\n}\n
Run Code Online (Sandbox Code Playgroud)\n

您可以使用以下方法执行相同操作getServerSideProps

\n
// pages/[id].js\n\nexport async function getServerSideProps(context) {\n  const { params } = context;\n  const id = params.id;\n\n  /* ... */\n}\n
Run Code Online (Sandbox Code Playgroud)\n