Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
785 views
in Technique[技术] by (71.8m points)

javascript - How to generate static pages with nested dynamic routes

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

Everything works till there.

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

Movies/ [moviesbygenrelist]/[movie-slug]

I am statically generating the site

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;


     }

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


 }
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...