next.js 浅路由

17 min read

浅层路由允许你改变URL而不需要再次运行数据获取方法,这包括getServerSideProps、getStaticProps和getInitialProps。

你将通过路由器对象(由useRouter或withRouter添加)收到更新的路径名和查询,而不会丢失状态。

要启用浅层路由,请将浅层选项设置为true。考虑一下下面的例子。

import { useEffect } from 'react'
import { useRouter } from 'next/router'

// Current URL is '/'
function Page() {
  const router = useRouter()

  useEffect(() => {
    // Always do navigations after the first render
    router.push('/?counter=10', undefined, { shallow: true })
  }, [])

  useEffect(() => {
    // The counter changed!
  }, [router.query.counter])
}

export default Page

URL将被更新为/?counter=10.而页面不会被替换,只有路由的状态被改变。

你也可以通过componentDidUpdate观察URL的变化,如下面所示:

componentDidUpdate(prevProps) {
  const { pathname, query } = this.props.router
  // verify props have changed to avoid an infinite loop
  if (query.counter !== prevProps.router.query.counter) {
    // fetch data based on the new query
  }
}

注意事项

浅层路由只对同一页面的URL变化起作用。例如,让我们假设我们有另一个名为pages/about.js的页面,而你运行这个。

router.push('/?counter=10', '/about?counter=10', { shallow: true })

由于这是一个新的页面,它将卸载当前页面,加载新的页面,并等待数据的获取,即使我们要求做浅层路由。