在 cookie/localSession 中存储选定的语言选项 [英] Storing selected language option in cookie/localSession
问题描述
我希望我的 Next.js 应用程序记住用户喜欢哪种语言,因此我想将它存储在客户端的 cookie 中.我有 2 种语言选项:EN &法国.
I would like my Next.js app to remember which language the user prefers, therefore I want to store it in a cookie on client side. I have 2 language options: EN & FR.
默认情况下,语言设置为英语(无 cookie,myapp.com/
),但一旦用户点击 EN 首选项,URL 将更改为 myapp.com/en
和这个选择的语言应该被存储.这同样适用于法语.
By default the language is set up for English (no cookie, myapp.com/
), but once the user clicks on EN preference, the URL changes to myapp.com/en
and this selected language should be stored. The same applies for French.
const [language, setLanguage] = useState(false);
<Link
href={`/${router.locale === 'en' ? 'fr' : 'en'}`}
locale={false}
>
<a
onClick={() => {
setLanguage((language) => !language);
// setCookie({});
}}
>
{` ${language ? 'en' : 'fr'}`}
</a>
我在哪里以及如何使用 cookie 或会话存储以便后端可以看到它?
Where and how can I use the cookie or session storage so the backend can see it?
推荐答案
如评论中所述,您可以利用 NEXT_LOCALE
cookie 来保留用户的语言首选项.这将覆盖 Next.js 内置 i18n 通常使用的 accept-language 标头.
As mentioned in the comments, you can leverage the NEXT_LOCALE
cookie to persist the user's language preference. This will override the accept-language header that is usually used by Next.js built-in i18n.
const setCookie = (locale) => {
document.cookie = `NEXT_LOCALE=${locale}; expires=Fri, 31 Dec 9999 23:59:59 GMT`
}
建议:与您提出的问题无关,我还建议您使用按钮而不是锚点来处理语言切换,因为此时它不仅仅是简单的导航.
Recommendation: Unrelated to the issue you raised, I would also recommend you use a button rather than an anchor to handle the language switching, as it's doing more than just simple navigation at this point.
<button
onClick={() => {
const locale = router.locale === 'en' ? 'fr' : 'en'
setCookie(locale)
router.push(`/${locale}`, `/${locale}`, { locale: false })
}}
>
{router.locale === 'en' ? 'fr' : 'en'}
</button>
这篇关于在 cookie/localSession 中存储选定的语言选项的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!