使用 Next JS 和 Commerce.js 获取产品永久链接和 ID

时间:2021-01-12 21:04:37

标签: javascript reactjs next.js e-commerce next-router

我想知道是否有人可以指出我正确的方向。我正在关注 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].js,其中 index.js 是所有产品页面。

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

这是 [name].js 页面:

import { useRouter } from "next/router";

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

  return <p></p>;
};

export default Product;

当然,这只是用我可以访问的内容注销对象。查询显示 [name]: "product-name",这很棒 - 我现在可以调用所有产品并过滤与此 slug 匹配的产品,但我想改用产品 id。 Commerce.js 有一个请求,我可以通过使用它的 requestid 单个产品。我该怎么办?

谢谢。

1 个答案:

答案 0 :(得分:2)

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

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

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

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

编辑:

如果您想要改进 SEO 的变通方法,您可以使用类似 products/[...slug].js 的结构,然后使用包罗万象的路径将类似于 /products/342/product-name 是一种妥协,但它可以与 SSR 一起使用。< /p>

相关问题