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

next.js - import Router from 'next/router' is it ok?

Next.js documentation mentions two ways to access the router object: useRouter for functional components and withRouter for class-based components.

However, it does not mention something I came across a few times which is the Router object accessed as follows, for example:

import Router from 'next/router'

Router.push("/")

Is it correct to use Router in this way? Why doesn't Next.js documentation mention it?

See Question&Answers more detail:os

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

1 Reply

0 votes
by (71.8m points)

I guess the main suggestion to not use Router.push() or Router.pathname directly from the object itself is because of the way Next.js serves the applications. When you're trying to do:

import Router from 'next/router';

const HomePage = () => {
  console.log(Router.pathname);

  return (
    <div>hi</div>
  )
}

You will receive an error with: You should only use "next/router" inside the client side of your app. This is because of the way next/router works with SSR.

You could however put this in an useEffect and it will work... but that's hacky and you will probably run into issues in the future.

Both useRouter and withRouter are Next.js their solution to this problem. They are both build so they can work with SSR and CSR. So my suggestion is just to use one of these, they work great ??.


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

...