Skip to content

Instantly share code, notes, and snippets.

@riskers
Last active January 5, 2022 09:23
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save riskers/efa3a83e9d314074bb00d47332be8e57 to your computer and use it in GitHub Desktop.
Save riskers/efa3a83e9d314074bb00d47332be8e57 to your computer and use it in GitHub Desktop.
自定义 React Hook - react-intl-universal 国际化

背景

使用 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;
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment