繁体   English   中英

是否可以在 next.js 中定义 hash 路由?

[英]Is it possible to define hash route in next.js?

I had already made a modal component with <HashRouter> in react-router that became active and inactive with hash url ie modals is inactive when url is /route and modal1 is active when url is /route#modal1 . 有什么方法可以在 next.js 中定义 hash 路由?

以哈希符号(标识 html 实体)开头的 url 部分永远不会发送到服务器,因此您无法匹配 url 服务器端(如果浏览器加载/route#modal1服务器将加载/route )您可以做什么做的是:

选项 1处理模态渲染客户端,在组件中使用next/router ,如下所示:
(我假设您正在使用类组件)

  import Router from 'next/router'

  ....

  componentDidMount(){
    let id = Router.asPath.match(/#([a-z0-9]+)/gi )
    if(id){
      // i will show the modal
    }else{
      // something else
    }
  }

选项 2将 id 传递给不带#的 url。
在你的server.js添加一个类似于这样的路由:

  server.get('/route/:id?', (req, res) => {
    let {id} =  req.params 
    return app.render(req, res, '/mypage', { id})
  })

然后获取 id,例如。 getInitialProps

  static async getInitialProps (context) {
    let ctx  = context.query;
    return ctx
  }

并处理模态

  componentDidMount(){
    let {id} =  this.props    
    if(id){
      // i will show the modal
    }else{
      // something else
    }
  }

您可以使用 next/router 添加哈希。

有些更改呈现基于状态的字符串组成部分,因此,以确保我知道我是哪条路线上(并保持后退按钮的工作),我想补充的状态串stage作为哈希的URL检测到时改变。

React.useEffect(() => {
  router.push(`/booking#${stage}`)
}, [stage])

不过,这只适用于客户端。

您可以使用next/router来完成此操作。

In our case we use hash routing on a specific page to render different components depending on the hash url, so the user can go back and forth using regular web navigations buttons

// page.js

export default function MyPage() {
  const router = useRouter();
  const hash = router.asPath.split('#')[1] || '';
  const showModal = hash === 'modal1' ? true : false;
  const openModal = () => {
    router.push({ hash: 'modal1' });
  }  
  return (
    <>
      <h1>MyPage</h1>
      <Button onClick={openModal}>Open Modal 🙂</Button>
      {showModal && <ModalOne />}
    </>
  )
}
// ModalOne.js

export default function ModelOne {
  const router = useRouter();
  const closeModal = () => {
    router.push({ hash: '' });
  }
  return (
    <>
        <h1>Hello Modal</h1>
        <Button onClick={closeModal}>Close Modal 🙃</Button>
    </>
  )
}

每次路由器 hash 更改时,都会触发重新渲染,以类似于您在 SPA 上所期望的方式打开模式

这还具有在移动设备上按下时关闭模式的额外好处,正如我们在用例中所期望的那样。

注意:我使用的是 nextjs 版本 12.1.0

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM