You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Next.js多参数动态路由配置问题:电商州/类型/分类路由适配

Next.js 多层级电商路由解析实现

在你的pages/[...slug].js文件中,核心是解析router.query.slug这个数组(catch-all路由会自动将URL分段转为数组),结合业务规则判断当前路由对应的商品类型、地区和分类,再获取对应数据。以下是具体实现步骤和代码示例:

1. 按slug数组长度匹配路由规则

slug数组的长度对应URL的层级,结合元素值可匹配你的4种需求:

  • 长度=1:数组元素为州代码(如['al'])→ 默认shop类型,展示该州全品类商品(对应规则1)
  • 长度=2:
    • 第二个元素是tailor(如['al', 'tailor'])→ tailor类型,展示该州定制类全品类(对应规则2)
    • 第二个元素是分类名(如['al', 'women'])→ 默认shop类型,展示该州对应分类商品(对应规则3)
  • 长度=3:第二个元素固定为tailor,第三个是分类名(如['al', 'tailor', 'women'])→ tailor类型,展示该州对应分类商品(对应规则4)

2. 代码实现示例

客户端渲染解析逻辑

import { useRouter } from 'next/router';

export default function ProductPage() {
  const router = useRouter();
  const slug = router.query.slug || [];
  let state, type = 'shop', category = null;

  // 解析路由参数
  switch (slug.length) {
    case 1:
      state = slug[0];
      break;
    case 2:
      state = slug[0];
      if (slug[1] === 'tailor') {
        type = 'tailor';
      } else {
        category = slug[1];
      }
      break;
    case 3:
      state = slug[0];
      if (slug[1] === 'tailor') {
        type = 'tailor';
        category = slug[2];
      } else {
        router.push('/404');
        return null;
      }
      break;
    default:
      router.push('/404');
      return null;
  }

  // 这里根据state、type、category调用数据接口获取商品
  // 示例:const products = await fetchProducts(state, type, category)

  return (
    <div>
      <h1>{state.toUpperCase()}州 {type === 'tailor' ? '定制' : '店铺'}类 {category ? category : '全品类'}商品</h1>
      {/* 商品列表渲染区域 */}
    </div>
  );
}

服务端渲染(getServerSideProps)解析逻辑

如果需要在服务端提前处理参数并获取数据,可使用getServerSideProps:

export async function getServerSideProps(context) {
  const { slug } = context.params;
  let state, type = 'shop', category = null;
  let isValidRoute = true;

  // 解析参数
  switch (slug.length) {
    case 1:
      state = slug[0];
      break;
    case 2:
      state = slug[0];
      if (slug[1] === 'tailor') {
        type = 'tailor';
      } else {
        category = slug[1];
      }
      break;
    case 3:
      state = slug[0];
      if (slug[1] === 'tailor') {
        type = 'tailor';
        category = slug[2];
      } else {
        isValidRoute = false;
      }
      break;
    default:
      isValidRoute = false;
  }

  // 校验州代码合法性(可扩展为全美国州代码数组)
  const validStates = ['al', 'ak', 'az'];
  if (!validStates.includes(state)) {
    isValidRoute = false;
  }

  if (!isValidRoute) {
    return { notFound: true };
  }

  // 调用接口获取商品数据
  // const products = await fetch(`/api/products?state=${state}&type=${type}&category=${category || ''}`)

  return {
    props: {
      state,
      type,
      category,
      // products,
    },
  };
}

3. 额外优化建议

  • 维护合法州代码和分类列表,在解析时校验参数有效性
  • 对非法路由直接返回404页面,提升用户体验

内容的提问来源于stack exchange,提问作者Raghwendra Ojha

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.14 04:27:32