首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >Next.js router.push不更改URL中的区域设置

Next.js router.push不更改URL中的区域设置
EN

Stack Overflow用户
提问于 2022-08-08 08:19:40
回答 1查看 416关注 0票数 -1

我通过将onClick绑定到两个<div>元素来更改区域设置:

代码语言:javascript
运行
复制
import { useRouter } from 'next/router'
// other codes

const router = useRouter()

const changeLocale = (locale) => {
    router.push({
        router: router.pathname,
        query: router.query
    }, router.asPath, { locale })
}

return <div>
    <div onClick={() => changeLocale('en')}>EN</div>
    <div onClick={() => changeLocale('ru')}>RU</div>
</div>

问题是它不改变URL。当我转到/en/about并单击这个RU时,URL不会变成/ru/about

为什么router.push不像预期的那样工作?

EN

回答 1

Stack Overflow用户

发布于 2022-08-08 09:49:04

router.push({})没有router属性!

若要处理路由,请提供区域设置列表,默认区域设置和Next.js将自动处理路由。

代码语言:javascript
运行
复制
// next.config.js
module.exports = {
  i18n: {
    // These are all the locales you want to support in
    // your application
    locales: ['en', 'ru'],
    // This is the default locale you want to be used when visiting
    // a non-locale prefixed path e.g. `/hello`
    defaultLocale: 'en',
  },
}

假设您正在使用next 12,若要向默认区域设置添加前缀,请更新您的下一个配置:

代码语言:javascript
运行
复制
// next.config.js

module.exports = {
  i18n: {
    locales: ['default', 'en', 'ru'],
    defaultLocale: 'default',
    localeDetection: false,
  },
  trailingSlash: true,
}

接下来,要添加自定义路由规则,请在页面中创建一个新文件middleware.js

代码语言:javascript
运行
复制
// middleware.js

import { NextRequest, NextResponse } from 'next/server'

const PUBLIC_FILE = /\.(.*)$/

export async function middleware(req: NextRequest) {
  if (
    req.nextUrl.pathname.startsWith('/_next') ||
    req.nextUrl.pathname.includes('/api/') ||
    PUBLIC_FILE.test(req.nextUrl.pathname)
  ) {
    return
  }

  if (req.nextUrl.locale === 'default') {
    return NextResponse.redirect(new URL(`/en${req.nextUrl.pathname}`, req.url))
  }
}

请访问nextjs docs以了解更多有关地区策略的信息。

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/73274826

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档