0

I have page which can have one of 2 params. email and hash if there are not present I want to redirect the user.

/confirm-email?email=user@email.com

I have tried the following:

const router = useRouter();
const { email, hash } = router.query;

useEffect(() => {
  if (!email && !hash) {
    router.push('/');
  } else if (hash) {
    // Do stuff
  }
}, [email, hash, router]);

But the problem on first render both of them are undefined and the user gets redirected even if the hash or email params are present.

How can I fix this ? any suggestions ?

4

2 回答 2

0

After doing some research. I have figured out it's best check if the params exists or not inside getServerSideProps()

export async function getServerSideProps({ query }) {
  if (!query.email && !query.hash) {
    return {
      notFound: true,
    };
  }

  return {
    props: {},
  };
}
于 2021-05-27T21:10:30.457 回答
-1
if (hash)

looks unecessary.

and

query: Object - The query string parsed to an object. It will be an empty object during prerendering if the page doesn't have data fetching requirements. Defaults to {}

is a quote from https://nextjs.org/docs/api-reference/next/router

I assume that is the location of the problem.

the param would be the file name in Router.query

for example:

import { useRouter } from 'next/router'

const Post = () => {
  const router = useRouter()
  const { pid } = router.query

  return <p>Post: {pid}</p>
}

export default Post

for the file [pid].js in pages/morepages/[pid].js

Or maybe, to use 2 param options you need to go to a website page that uses both. So there has to be a hashtag between them.

Such as "website/emial/hash"

于 2021-05-27T18:39:06.543 回答