如何生成带有嵌套动态路由的静态页面 [英] How to generate static pages with nested dynamic routes

查看:54
本文介绍了如何生成带有嵌套动态路由的静态页面的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我一直在这个网站上工作,但遇到了障碍.基本上我应该按类型列出电影,从数据库中获取.流派应该带我到另一个基于流派的列表.一旦用户单击动作"类型的电影,就会将他们带到另一个页面上的电影详细信息.这是结构

I have been working on this site and I have hit a wall. Basically I am supposed to list movies by genre, fetched from database. The genre should take me to another list based on the genre. Once a user clicks the movie from say 'action' genre it takes them to the movie details on another page. This is the structure

Movies/ [moviesbygenrelist]/list

一切正常.

转到第二个动态页面我无法获取第一个和第二个动态页面的值如下...

Moving on to the second dynamic page I cannot get values of first and second dynamic page as below...

Movies/ [moviesbygenrelist]/[movie-slug]

我正在静态生成网站

如何在第二个动态页面上获取第一页的参数

how can i get parameters of first page while on the second dynamic page

这就是我所拥有的,我先打电话

This is what i have, I first call

 let movieTypeID;
 let movieSlug;
    export async function getStaticProps({params}) {

        movieTypeID=params.movietype;
        movieSlug=params.movie;


     }

我的逻辑是我可以从 getStaticProps 但不能在 getStaticPaths 中访问路由参数,所以我先调用它,实例化变量,然后将它们传递给 getStaticPaths,这样我就可以使用变量进行数据库调用,因为我现在在数据库中有点深.没有动态参数我无法拨打电话我像下面这样传递它们

my logic is i can access route parameters from getStaticProps but not in getStaticPaths so I call it first, instantiate the variables then pass them to getStaticPaths so I can make database calls using the variables since I am now a bit deep in the database. I cannot make calls without the dynamic parameters I pass them like below

export async function getStaticPaths(movieTypeID, movieSlug) {

///only they come out as undefined


 }

推荐答案

假设页面位于 Next.js 应用程序中的 pages/movies/[type]/[slug].jsx 下:

Assuming the page is located under pages/movies/[type]/[slug].jsx in your Next.js app:

// pages/movies/[type]/[slug].jsx
export async function getStaticPaths() {
  const movies = db.getAllMovies() // Retrieve all movies data from database
  const paths = movies.map((movie) => ({
    params: { type: movie.type, slug: movie.slug },
  }))

  return {
    paths,
    fallback: false // Paths not returned will result in a 404
  };
}

export async function getStaticProps({ params }) {
  const { type, slug } = params
  const movieData = getMovie(type, slug) // Retrieve data for given type/slug pair

  return {
    props: {
      data: movieData
    }
  }
}

function Movie({ data }) {
  //render the given movie data
}

export default Movie

这将为您数据库中的所有电影静态生成页面.每个页面都将在浏览器中的 /movies// 中可用.

This will statically generate pages for all movies in your database. Each page will be available at /movies/<movie-type>/<movie-slug> in the browser.

这篇关于如何生成带有嵌套动态路由的静态页面的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆