简体   繁体   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 . 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 . There is any ways to define hash routes in next.js?有什么方法可以在 next.js 中定义 hash 路由?

The part of the url starting with the hash symbol (that identifies an html entity) is never sent to the server, so you cant match the url serverside (if the browser loads /route#modal1 the server will load /route ) what you can do is :以哈希符号(标识 html 实体)开头的 url 部分永远不会发送到服务器,因此您无法匹配 url 服务器端(如果浏览器加载/route#modal1服务器将加载/route )您可以做什么做的是:

Option 1 Handle the modal rendering client side, using next/router in your component with something like this :选项 1处理模态渲染客户端,在组件中使用next/router ,如下所示:
(im assuming you are using class components) (我假设您正在使用类组件)

  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
    }
  }

Option 2 Pass the id to the url without # .选项 2将 id 传递给不带#的 url。
In your server.js add a route similar to this :在你的server.js添加一个类似于这样的路由:

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

And then grab the id, ex.然后获取 id,例如。 in getInitialPropsgetInitialProps

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

And handle the modal并处理模态

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

You can add a hash using the next/router.您可以使用 next/router 添加哈希。

Some pages I change the component that renders based on a state string, so to make sure I know which route I'm on (and keep the back button working) I add a state string stage as a hash to the URL when it detects a change.有些更改呈现基于状态的字符串组成部分,因此,以确保我知道我是哪条路线上(并保持后退按钮的工作),我想补充的状态串stage作为哈希的URL检测到时改变。

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

This will only work client side though.不过,这只适用于客户端。

You can use next/router to accomplish that.您可以使用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 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>
    </>
  )
}

Every time the router hash changes a re render is triggered, opening the modal in a similar way to what you would expect on a SPA每次路由器 hash 更改时,都会触发重新渲染,以类似于您在 SPA 上所期望的方式打开模式

This also has the added benefit of closing the modal when pressing back on a mobile device, as it was in our use case expectations.这还具有在移动设备上按下时关闭模式的额外好处,正如我们在用例中所期望的那样。

Note: I'm using nextjs version 12.1.0注意:我使用的是 nextjs 版本 12.1.0

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

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