大佬教程收集整理的这篇文章主要介绍了如何在 Next.js 中重新加载时强制执行 i18n 区域设置并实现 i18n 一致性?,大佬教程大佬觉得挺不错的,现在分享给大家,也给大家做个参考。
我正在使用 next-translate
。默认情况下,我的路线识别如下:
/about <---
/de/about
/es/about
但我想为所有路径强制执行区域设置:
/en/about <---
/de/about
/es/about
这是我的配置:
next.config.Js
const nextTranslate = require('next-translate');
module.exports = nextTranslate({
...
i18n: {
localeDetection: false,locales: ['en','de','es'],defaultLocale: 'en',}
});
i18n.Js
@H_672_3@module.exports = { locales: ['en',pages: { '*': ['common'] },interpolation: { prefix: '${',suffix: '}',},loadLocaleFrom: (locale,namespacE) => import(`./translations/${localE}/${namespacE}`).then((m) => m.default),}
请注意,我还有一个 lang 更改组件,用于保留 NEXT_LOCALE
cookie。因此,我希望当我访问 /about
并且我的 NEXT_LOCALE
cookie 之前已设置为 de
时,路由器会将我重定向到 /de/about
。 但它没有。它停留在 /about
并将 cookie 重写为 en
...
这是当前的 pages
文件夹结构:
...
pages/
_app.tsx
_document.tsx
about.tsx
...
我需要将其重组为这个吗?
pages/
_app.tsx
_document.tsx
[lang]/ <---
about.tsx
...
如果是这样,下一步是什么?
useRouter()
解析首选语言环境NEXT_LOCALE
cookielang
slug然后决定哪个具有更高的优先级?我应该在哪里做?在 _app.tsx
/ 一些 HOC 中?
我的 rewrites
中是否需要任何 redirects
或 next.config.Js
,还是应该通过 Router.push
动态处理这些?
持久化的 NEXT_LOCALE
cookie 不会根据其值自动重定向的事实是因为您已通过设置 localeDetection: false
显式禁用它。这会影响基于标头的重定向以及基于 cookie 的重定向。
只需将其从您的 next.config.js
中删除即可解决该问题。
const nextTranslate = require('next-translate');
module.exports = nextTranslate({
...
i18n: {
locales: ['en','de','es'],defaultLocale: 'en',}
});
没有内置的方法可以在所有路径上强制使用默认语言环境。但是,您可以检查默认语言环境,并在第一次通过 router.push
挂载时在 URL 中明确设置它。
让我们假设以下自定义 useDefaultLocale
钩子抽象了要重用的逻辑。
import { useState,useEffect } from 'react';
import { useRouter } from 'next/router';
export const useDefaultLocale = () => {
const router = useRouter();
useEffect(() => {
if (router.locale === router.defaultLocalE) {
router.push(`/${router.localE}${router.asPath}`,undefined,{
locale: false,shallow: true // Optionally add this if you don't want to rerun data fetching methods
});
}
},[]);
};
然后可以在您的网页或 _app.js
中使用。
import { useDefaultLocale } from '<path-to>/use-default-locale';
const AboutPage = () => {
useDefaultLocale()
return <>About Page</>;
};
以上是大佬教程为你收集整理的如何在 Next.js 中重新加载时强制执行 i18n 区域设置并实现 i18n 一致性?全部内容,希望文章能够帮你解决如何在 Next.js 中重新加载时强制执行 i18n 区域设置并实现 i18n 一致性?所遇到的程序开发问题。
如果觉得大佬教程网站内容还不错,欢迎将大佬教程推荐给程序员好友。
本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。