我通过将onClick
绑定到两个<div>
元素来更改区域设置:
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
不像预期的那样工作?
发布于 2022-08-08 01:49:04
注
router.push({})
没有router
属性!
若要处理路由,请提供区域设置列表,默认区域设置和Next.js将自动处理路由。
// 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,若要向默认区域设置添加前缀,请更新您的下一个配置:
// next.config.js
module.exports = {
i18n: {
locales: ['default', 'en', 'ru'],
defaultLocale: 'default',
localeDetection: false,
},
trailingSlash: true,
}
接下来,要添加自定义路由规则,请在页面中创建一个新文件middleware.js
:
// 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))
}
}
https://stackoverflow.com/questions/73274826
复制