使用 react-intl-universal 作为国际化的方案,但是我需要在每次切换语言的时候不刷新页面替换文字,就是这种效果:
而官方是这么做的: Gihub demo,这样会刷新页面!
所以要自己实现了监听 cookie 的动作
lang 信息我存在 cookie 里:
而我的项目用了 hook ,所以要自己用 React Hook 实现:
使用 react-intl-universal 作为国际化的方案,但是我需要在每次切换语言的时候不刷新页面替换文字,就是这种效果:
而官方是这么做的: Gihub demo,这样会刷新页面!
所以要自己实现了监听 cookie 的动作
lang 信息我存在 cookie 里:
而我的项目用了 hook ,所以要自己用 React Hook 实现:
| import { useCookies } from "react-cookie"; | |
| import { Tab, TabList, TabPanel, Tabs } from "react-tabs"; | |
| import styles from "./style.module.css"; | |
| import { useLocale } from "@/locales/i18n"; | |
| const App = () => { | |
| // 这里获取 intl | |
| const __ = useLocale(); | |
| return <div> | |
| <h2>{__.get("NEWS_TITLE")}</h2> | |
| </div> | |
| } |
| import intl from "react-intl-universal"; | |
| import en from "@/locales/en.json"; | |
| import cn from "@/locales/zh-cn.json"; | |
| import { useCookies } from "react-cookie"; | |
| import { useEffect, useRef } from "react"; | |
| const getIntl = (lang: string) => { | |
| intl.determineLocale({ | |
| cookieLocaleKey: "lang", | |
| }); | |
| intl.init({ | |
| currentLocale: lang, | |
| locales: { | |
| "en-us": en, | |
| "zh-cn": cn, | |
| }, | |
| }); | |
| return intl; | |
| }; | |
| export const useLocale = () => { | |
| // 通过一个现成的包监听 cookies | |
| const [cookies] = useCookies([lang]); | |
| // 得到当前的 lang | |
| const lang = cookies[lang]; | |
| const ref = useRef<any>(); | |
| // 生成一个 intl 返回 | |
| ref.current = getIntl(lang); | |
| return ref.current; | |
| }; |