我认为通过路由器进行客户端导航和使用中间件存在问题。
不知何故,路由器会记住它第一次被重定向的时间,并且在接下来的时间里它会直接导航到该路由,而无需通过中间件。
当我刷新浏览器时,这种情况就会停止发生。
如果我在开发环境中运行,也不会发生这种情况。
我想强制路由器每次都进入中间件以重新评估重定向的位置。
重现:
- Go to
/
反复从浏览器搜索栏中搜索。您有 50% 的机会被重定向到/dashboard
以及 50% 至/profile
因为middleware.ts
- Go to
/login
并单击登录按钮。这将使router.push('/')
并被重定向到/dashboard
or /profile
.
- 单击注销按钮。这将使
router.push('/login')
.
- 下次登录时将始终重定向到相同的路由。
这是我的中间件.ts:
export function middleware(request: NextRequest) {
if (request.nextUrl.pathname === '/') {
if (Math.random() > 0.5) {
return NextResponse.redirect(new URL('/dashboard', request.url))
} else {
return NextResponse.redirect(new URL('/profile', request.url))
}
}
}
My 登录.tsx:
import { NextPage } from 'next'
import { useRouter } from 'next/router'
const LoginPage: NextPage<{}> = () => {
const router = useRouter()
const login = () => {
router.push('/')
}
return (
<div>
<h1>Login</h1>
<button onClick={login}>Login</button>
</div>
)
}
export default LoginPage
和仪表板/配置文件页面:
import { NextPage } from 'next'
import { useRouter } from 'next/router'
const DashboardPage: NextPage<{}> = () => {
const router = useRouter()
const logout = () => {
router.push('/login')
}
return (
<div>
<h1>DashboardPage</h1>
<button onClick={logout}>Logout</button>
</div>
)
}
export default DashboardPage
这是 Vercel 中显示的站点:https://nextjs-router-clientside-test.vercel.app/ https://nextjs-router-clientside-test.vercel.app/
这是完整的代码:https://github.com/LautaroRiveiro/nextjs-router-clientside-test https://github.com/LautaroRiveiro/nextjs-router-clientside-test