Reactjs - 如何使用动态值访问 json 中的嵌套键

我已经创建了一个 React 上下文来访问 i18n 翻译,以及一个名为“t”的函数来访问所需的值。它适用于简单键,但不适用于嵌套键。这是我的背景:


export function I18nProvider({ children }) {

  const [locale, setLocale] = useState<Locales>("en");

  const translations = { ch, fr, sw, en };

  return (

    <I18nContext.Provider value={{ translations, locale, setLocale }}>

      {children}

    </I18nContext.Provider>

  );

}


export function t(key: string) {

  const { translations, locale } = useContext(I18nContext);

  return useMemo(() => translations[locale][key], [locale, translations, id]);

}

这里是 t() 在行动:


<div>{t("form.username")}</div>;

显然,它不能工作,因为t()返回translations["en"]["form.username"]不正确。我试图在t()参数中允许子字段:t("form", "username")并返回translations[locale][key][sub]. 它有效,但是当我使用单个密钥时失败了。


如何使 t() 通用?我考虑过重新格式化我的 t 参数,但如果每次翻译都运行这样的操作,我担心它会影响性能。


富国沪深
浏览 152回答 1
1回答

Smart猫小萌

尝试使用一个辅助函数,它接受对象和返回深度值的路径作为参数:并像这样使用它:export function t(key: string) {&nbsp; const { translations, locale } = useContext(I18nContext);&nbsp; return useMemo(() => getDeepNestedFieldValue(locale+'.'+key,translations), [locale, translations, id]);}纯 JS 中的示例:const getDeepNestedFieldValue = (path, obj) => {&nbsp; return path.split('.').reduce((p, c) => (p && p[c]) || null, obj);}let user = {&nbsp; name: {&nbsp; &nbsp; first: 'John',&nbsp; &nbsp; last: 'Doe'&nbsp; },&nbsp; address: {&nbsp; &nbsp; city: {&nbsp; &nbsp; &nbsp; name: 'Cairo',&nbsp; &nbsp; }&nbsp; }}console.log(getDeepNestedFieldValue('name.first', user))console.log(getDeepNestedFieldValue('address.city.name', user))
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript