繁体   English   中英

使用 Next JS 和 Commerce.js 获取产品固定链接和 ID

[英]Get product permalink and ID using Next JS and Commerce.js

我想知道是否有人能指出我正确的方向。 我正在关注 Next JS 站点上的动态路由文档 - https://nextjs.org/docs/routing/dynamic-routes

目前我正在渲染products页面上的所有产品。 我正在使用getServersideProps进行 API 调用。 这是产品页面:

import Link from "next/link";

const Products = ({ data }) => {
  const products = data;
  return (
    <>
      {products.map(({ id, name, seo: { description } }) => (
        <div className="product" key={id}>
          <h2>{name}</h2>
          <p>{description}</p>
          <Link href={`/products/${permalink}`}>
            <a>View</a>
          </Link>
        </div>
      ))}
    </>
  );
};

export async function getServerSideProps() {
  const headers = {
    "X-Authorization": process.env.CHEC_API_KEY,
    Accept: "application/json",
    "Content-Type": "application/json",
  };
  const res = await fetch("https://api.chec.io/v1/products", {
    method: "GET",
    headers: headers,
  });
  const data = await res.json();

  if (!data) {
    return {
      redirect: {
        destination: "/",
        permanent: false,
      },
    };
  }

  return {
    props: data, // will be passed to the page component as props
  };
}

export default Products;

在链接中,我使用永久链接将人们引导至单个产品

<Link href={`/products/${permalink}`}>
            <a>View</a>
          </Link>

这在结构中设置为products/[name].jsindex.js是所有产品页面。

现在,在我的单个产品页面[name].js上,我想运行另一个getServersideProps来调用permalink/slug并获取产品 - 但我想使用product id ,但我只想在URL。

这是[name].js页面:

import { useRouter } from "next/router";

const Product = () => {
  const router = useRouter();
  console.log(router);

  return <p></p>;
};

export default Product;

当然,这只是用我可以访问的方式注销 Object。 查询显示 [name]: "product-name",这很好——我现在可以调用所有产品并过滤与此 slug 匹配的产品,但我想改用产品id Commerce.js 有一个请求,我可以仅通过使用它的idrequest单个产品。 我怎么会go这个呢?

谢谢。

我想你会遇到 SSR 的问题,如果你想传递 id 并且只显示 URL 中的 slug,如果没有人在那里传递它,SSR 将如何知道你的 ID?

您可以尝试这样的操作,但它只能在 SPA 模式下工作。

<Link href={{ pathname: '/products' query: { prodId: id} }} as={permalink} />

我认为如果你想让 SSR 工作,你不能隐藏 ID 表单 URL。

编辑:

如果你想要一个改进 SEO 的解决方法,你可以有一个像products/[...slug].js这样的结构,然后使用 catch-all 你的路径就像/products/342/product-name是一个妥协,但它会与SSR一起工作。

暂无
暂无

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

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