我最近將 React 應用程式遷移到 nextjs。
在那里,我們將HashRouter與 nextjs 路由器進行了交換。
當有人深度鏈接到我們的頁面時,我希望將 URL 轉發到不帶 # 的路由。
示例:轉發/#/contact
到/contact
在 next.config.js 中重定向
首先,我嘗試了以下內容next.config.js
:
module.exports = {
async redirects() {
return [
{
source: '/#/:slug*',
destination: '/:slug*',
permanent: true
}
]
}
}
--> 但這不起作用,因為下一個路由器忽略了 url 的 # 部分。
在 _app.tsx 內重定向
然后我寫了一個自定義鉤子useHashRouterRedirects.ts
。
import { useEffect } from 'react'
import { useRouter } from 'next/router'
/**
* Redirecting the old routes # router URLs to the new nextjs urls.
* (This does not work within the next.config.js)
*/
export const useHashRouterRedirects = () => {
const { push } = useRouter()
useEffect(() => {
const hashRoute = window.location.hash
if (hashRoute.includes('#')) {
const routeWithoutHash = hashRoute.replace('#', '')
push(routeWithoutHash)
}
}, [])
}
然后將其匯入_app.tsx
useHashRouterRedirects()
--> 但這會先加載舊頁面,然后再加載新頁面。它應該更快地轉發 URL。
什么更好?
關于如何重定向 # 路線還有其他選擇嗎?
uj5u.com熱心網友回復:
哈希路由只能在客戶端處理。
以下解決方案立即重定向并且不首先加載上一頁。
在公用檔案夾中添加一個新檔案。
public/hash-router-redirect.js
if (window.location.hash.includes('#')) {
const routeWithoutHash = window.location.hash.replace('#', '')
window.location.replace(routeWithoutHash)
}
在您的頁面檔案夾中導航到或創建)_document.js
webview/src/pages/_document.tsx
import { Html, Head, Main, NextScript } from 'next/document'
export default function Document() {
return (
<Html>
<Head>
...
<script async type='text/javascript' src='/hash-router-redirect.js'></script>
</Head>
<body>
<Main />
<NextScript />
</body>
</Html>
)
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/488105.html