0

我想知道是否有人可以指出我正确的方向。我正在关注 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 并获取产品 - 但我想使用但我只想在 URLproduct id中显示。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 有一个请求,我可以request通过使用它的id. 我该怎么办?

谢谢。

4

1 回答 1

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。

于 2021-01-12T21:30:15.280 回答