next.js 浅链接不与根中的中间件一起工作

yv5phkfx  于 2023-04-30  发布在  其他
关注(0)|答案(1)|浏览(116)

Shallow选项在我的项目./src/middleware.ts的根目录下的中间件不起作用

浏览器中的链接正在更改,但没有更新页面。
我使用侧边栏中的NextLink在页面之间导航,例如:

<NextLink href='/dashboard' passHref shallow>Dashboard</NextLink>
<NextLink href='/users' passHref shallow>Users</NextLink>
<NextLink href='/users' passHref shallow>Posts</NextLink>

此外,我尝试使用router.push,使用shallow on元素进行导航,如button或div:

<Button onClick={() => router.push('/dashboard', {}, { shallow: true })}>Dashboard</Button>
import { NextResponse, NextMiddleware } from 'next/server';

const PUBLIC_FILE = /\.(.*)$/;
export const middleware: NextMiddleware = (req) => {
  const acceptLanguage =
    req?.headers?.get('accept-language') &&
    req?.headers?.get('accept-language')?.slice(0, 2);

  if (
    req.nextUrl.pathname.startsWith('/_next') ||
    req.nextUrl.pathname.includes('/api/') ||
    PUBLIC_FILE.test(req.nextUrl.pathname)
  ) {
    return;
  }

  if (req.nextUrl.locale === 'default') {
    const newUrl = req.nextUrl.clone();
    
    newUrl.locale = acceptLanguage || 'en';
    
    return NextResponse.redirect(newUrl);
  }
};

"next": "^12.3.4",
"next-translate": "^2.0.4",
"react": "^17.0.2",
"react-dom": "^17.0.2"
oprakyz7

oprakyz71#

浅路由不用于页面之间的导航。它只是在客户端更新当前页面的路径,例如,更新查询参数,就像他们在documentation上说的那样:
浅路由允许您更改URL,而无需再次运行数据获取方法,包括getServerSidePropsgetStaticPropsgetInitialProps
您将通过router对象(由useRouterwithRouter添加)接收更新的pathnamequery,而不会丢失状态。
如果你在没有中间件的情况下使用它,你会得到下面的行为,比如shallow没有设置:
浅层路由仅适用于当前页面中的URL更改。例如,假设我们有另一个名为pages/about.js的页面,您运行以下命令:

router.push('/?counter=10', '/about?counter=10', { shallow: true })

由于这是一个新页面,它将卸载当前页面,加载新页面并等待数据获取,即使我们要求进行浅路由。
当涉及到中间件时,它将无法正常工作,正如他们在文档中特别指出的那样:
当浅路由与中间件一起使用时,它将不能确保新页面与当前页面匹配,就像以前没有中间件一样。这是由于中间件能够动态重写,并且在没有数据获取的情况下无法在客户端验证,而数据获取是用浅路由跳过的,因此浅路由更改必须始终被视为浅路由。

相关问题