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
文件。
如果您的页面使用动态路由,params
请包含路由参数。例如,如果页面名称是[id].js
,则将params
如下所示:
{ id: /* something */ }\n
Run Code Online (Sandbox Code Playgroud)\n您可以使用上下文参数从或函数内部获取URL 参数。\nHere\xe2\x80\x99s 是一个示例:getStaticProps
getServerSideProps
getStaticProps
// 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
:
// 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
归档时间: |
|
查看次数: |
4507 次 |
最近记录: |