使用方式:
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
:事件监听器url
: 路径as
:dom 中标签options
:路由配置shallow
:是否深度渲染,默认为 false,更新路由时,会重新调用getStaticProps
, getServerSideProps
, getInitialProps
并渲染新的页面。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>
)
}