【问题标题】:NextJs nested dynamic routes based on APINextJs 基于 API 的嵌套动态路由
【发布时间】:2021-09-21 01:36:18
【问题描述】:

我被 Nextjs 困住了:我需要根据我的(本地)数据创建嵌套的动态路由。

这是我想创建的路线:

  1. .../cars/ -> 显示所有类别(轿车、SUV、4x4)

  2. .../cars/category/ -> 在类别中显示汽车

    ex : .../cars/sedan -> 显示轿车类别中的汽车

  3. .../cars/category/id -> 从 id = 1 的类别中显示汽车的详细信息

    ex : .../cars/sedan/1 -> 显示 id = 1 的轿车的详细信息

路线 1 和 2 没问题,但我不知道如何做最后一个。你能帮帮我吗?

data.js

export const cars = [
  {
    id: 1,
    name: 'sedan',
    models: [
      {
        id: 1,
        name: 'model1',
        image: '/sedan1.jpg',
      },
      {
        id: 2,
        name: 'model2',
        image: '/sedan2.jpg',
      },
      {
        id: 3,
        name: 'model3',
        image: '/sedan3.jpg',
      },
    ],
  },
  {
    id: 2,
    name: 'suv',
    models: [
      {
        id: 1,
        name: 'model1',
        image: '/suv1.jpg',
      },
      {
        id: 2,
        name: 'model2',
        image: '/suv2.jpg',
      },
      {
        id: 3,
        name: 'model3',
        image: '/suv3.jpg',
      },
    ],
  },
  {
    id: 3,
    name: '4x4',
    models: [
      {
        id: 1,
        name: 'model1',
        image: '/4x4_1.jpg',
      },
      {
        id: 2,
        name: 'model2',
        image: '/4x4_2.jpg',
      },
      {
        id: 3,
        name: 'model3',
        image: '/4x4_3.jpg',
      },
    ],
  },
];

/cars/index.js

import { cars } from '../../data';
import Link from 'next/link';

export default function Categories({ car }) {
  return (
    {car.map((c) => (
      <Link key={c.id} href={`/cars/${c.name}`} passHref>
        <div>{c.name}</div>
      </Link>
    ))}
  );
}

export const getStaticProps = async () => {
  return {
    props: {
      car: cars,
    },
  };
}; 

/cars/[name].js

import React from 'react';

import { cars } from '../../data';

export default function CategoriesCars({ cars }) {
  return (
    <div>
      {cars.models.map((m) => (
        <p key={m.id}>{m.name}</p>
      ))}
    </div>
  );
}

export const getStaticPaths = async () => {
  const paths = await cars.map((c) => ({
    params: {
      name: c.name,
    },
  }));
  return { paths, fallback: false };
};

export const getStaticProps = async (context) => {
  const { params } = context;
  const response = await cars.filter((c) => c.name === params.name);
  return {
    props: {
      cars: response[0],
    },
  };
};

【问题讨论】:

    标签: reactjs routes next.js nested-routes


    【解决方案1】:

    页面文件夹必须是:

    pages/
     cars/
      [category]/
       [id]/
        index.jsx
       index.jsx
    

    然后去/cars/sedan/2你可以访问categoryid这样的变量:

    汽车/[类别]/[id]/index.jsx

    import React from 'react';
    import { useRouter } from 'next/router';
    
    export default function Index() {
      const router = useRouter();
      // router.query.category -> sedan
      // router.query.id -> 2
      return <div>{JSON.stringify(router.query)}</div>;
    }
    
    // or 
    export const getServerSideProps = async (context) => {
      const { params } = context;
      console.log(params); // { category: 'sedan', id: '2' }
      return {
        props: {
          cars: {},
        },
      };
    };
    
    // or if you wish use getStaticProps for SSG (with getStaticPaths)
    export const getStaticPaths = async (context) => {
      const paths = cars
        .map((car) =>
          car.models.map((model) => ({
            params: {
              id: model.id.toString(),
              category: car.name,
            },
          }))
        )
        .flat(); // this is important
    
      return { paths, fallback: false };
    };
    
    export const getStaticProps = async (context) => {
      const { params } = context;
      console.log(params);
      return {
        props: {
          cars: {},
        },
      };
    };
    
    

    示例:StackBlitz

    【讨论】:

    • 感谢您的回复。我无法使您的示例适应我的代码。你正在使用getServerSideProps,而我需要getStaticPathsgetStaticProps。此外,当我尝试您的指令时,我收到一条错误消息Error: A required parameter (category) was not provided as a string in getStaticPaths for / cars / [category]
    • 我已经编辑了示例。您只需提供基于数据的路径。这里:stackblitz
    • 感谢您的帮助!
    猜你喜欢
    • 1970-01-01
    • 2021-05-05
    • 1970-01-01
    • 1970-01-01
    • 2021-03-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-01-20
    相关资源
    最近更新 更多