Manon.icu

I'm here to make you a better developer by teaching you everything I know about building for the web.

Published 2022-05-21

Next.js - how-to-programmatically-navigate-in-next-js

useRouter 钩子

使用方式:

import {useRouter} from 'next/router'

export default function Home() {
  const router = useRouter()
  console.log(router)
  return <></>
}

useRouter钩子返回一个对象,包含了路由相关的信息,包括:

  • router.query:路由参数
  • router.pathname:路由路径
  • router.asPath:当前页面的完整路径
  • router.route:当前路由的路径
  • router.events:事件监听器

router.push

  • url: 路径
  • as:dom 中标签
  • options:路由配置
  • shallow:是否深度渲染,默认为 false,更新路由时,会重新调用getStaticProps, getServerSideProps, getInitialProps并渲染新的页面。

router.replace

router.replace方法类似于router.push,但是会替换当前的路由,而不是增加一个新的路由。

<video src="https://cdn.jsdelivr.net/gh/manonicu/pics@master/uPic/Next.js-navigate-programmatically.mp4" controls width={640} height={320} autoPlay

代码

feedback.js

const FeedBack = (props) => {
  return (
    <div style={{padding: 50}}>
      <h1>Feedback Page</h1>
    </div>
  )
}

export default FeedBack

index.js

import {useRouter} from 'next/router'

export default function Home() {
  const router = useRouter()
  return (
    <div style={{padding: 50}}>
      <h1>Home Page</h1>
      <h2>push()</h2>
      <p>
        <button onClick={() => router.push('/feedback')}>
          Go to the feedback page
        </button>
      </p>
      <p>
        <input type="checkbox" onChange={() => router.push('/feedback')}></input>{' '}
        Check me to go to the feedback page
      </p>
      <br />

      <h2>replace()</h2>
      <div>
        <button onClick={() => router.replace('/feedback')}>
          Go to the feedback page and not go back
        </button>
      </div>
    </div>
  )
}

Comments

No Comments!