簡體   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