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
754 views
in Technique[技术] by (71.8m points)

reactjs - ID is gone when I refresh a NextJS Dynamic Route page

I am trying to get dynamic routing working in order to display and retrieve the right information using the id from the url. This works when I visit the page, but when I reload the page the id is blank. Is this fixable? I couldn't find a answer for it on the internet.

Any help would be appreciated.

Code for reference

//Initializing router
const router = useRouter();

//Getting id from url
const { id } = router.query;

//Fetching postdata
  const getPostData = async () => {
    setLoading(true);
    await db
      .collection("Posts")
      .doc(id)
      .get()
      .then(function (doc) {
        if (doc.exists) {
          setPostData(doc.data());
          setLoading(false);
        } else {
          //router.push("/404");
        }
      })
      .catch(function (error) {
        //router.push("/404");
      });
  };
question from:https://stackoverflow.com/questions/65859612/id-is-gone-when-i-refresh-a-nextjs-dynamic-route-page

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

1 Answer

0 votes
by (71.8m points)

This is a known caveat about Next.js routing, you can read about it here.

Anyway, add this on your page that uses router.query:

export async function getServerSideProps(context) {
    return {
        props: {},
    };
}

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

...