Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

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

reactjs - Nextjs getStaticPaths (Static Generation)

link to docs

assume following directory structure

pages
  animals
    [animalName].tsx
  index.tsx

my [animalName].tsx

import { useRouter } from "next/router";
import { GetStaticPaths, GetStaticProps } from "next";

export const sleep = (ms: number) =>
  new Promise((resolve) => setTimeout(resolve, ms));

export const getStaticProps: GetStaticProps = async ({params}) => {
  await sleep(5000);
  return {
    props: {
      name: params.animalName,
    },
  };
};

export const getStaticPaths: GetStaticPaths = async () => {
  return {
    // only /animals/lion will be statically generated
    paths: [{ params: { animalName: "lion" } }],
    fallback: true,
  };
};

function AnimalName(props) {
  const router = useRouter();

  if (router.isFallback) {
    return <h1>Loading...</h1>;
  }

  return (
    <div>
      <h1>animal name from server - {props.name}</h1>
    </div>
  );
}

export default AnimalName;

assume i have

two links in my index.tsx

  1. /animals/lion
  2. /animals/tiger

my expectation

  1. on clicking on /animals/tiger, i would first see Loading... for 5 seconds then the component gets rerendered with new props

  2. on clicking on /animals/lion, the page will be stuck at index page for 5 seconds then sudenly i will be migrated to /animals/lion

what happens -

in both cases, the page is stuck at index page for 5 seconds then sudenly i am migrated to /animals/whatever

what i expected happens if i am trying to type the url directly in the address bar..

why is this behavior hapenning...am i missing something ?

can someone elaborate further...

thanks!!!

question from:https://stackoverflow.com/questions/65839319/nextjs-getstaticpaths-static-generation

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

1 Answer

0 votes
by (71.8m points)
Waitting for answers

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...