【问题标题】:Get product permalink and ID using Next JS and Commerce.js使用 Next JS 和 Commerce.js 获取产品永久链接和 ID
【发布时间】:2021-04-17 21:09:00
【问题描述】:

我想知道是否有人能指出我正确的方向。我正在关注 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 来调用 API 并获取产品 - 但我想使用 product id 但是我只想显示 @网址中的 987654331@。

这里是[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 有一个请求,我只需使用其id 即可request 单个产品。我该怎么办?

谢谢。

【问题讨论】:

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


    【解决方案1】:

    我认为你在使用 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。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-04-23
      • 1970-01-01
      • 1970-01-01
      • 2015-12-10
      • 1970-01-01
      相关资源
      最近更新 更多