第七色在线视频,2021少妇久久久久久久久久,亚洲欧洲精品成人久久av18,亚洲国产精品特色大片观看完整版,孙宇晨将参加特朗普的晚宴

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

Reactjs - 如何使用動態(tài)值訪問 json 中的嵌套鍵

Reactjs - 如何使用動態(tài)值訪問 json 中的嵌套鍵

富國滬深 2022-07-15 10:18:22
我已經(jīng)創(chuàng)建了一個 React 上下文來訪問 i18n 翻譯,以及一個名為“t”的函數(shù)來訪問所需的值。它適用于簡單鍵,但不適用于嵌套鍵。這是我的背景: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()參數(shù)中允許子字段:t("form", "username")并返回translations[locale][key][sub]. 它有效,但是當我使用單個密鑰時失敗了。如何使 t() 通用?我考慮過重新格式化我的 t 參數(shù),但如果每次翻譯都運行這樣的操作,我擔(dān)心它會影響性能。
查看完整描述

1 回答

?
Smart貓小萌

TA貢獻1911條經(jīng)驗 獲得超7個贊

嘗試使用一個輔助函數(shù),它接受對象和返回深度值的路徑作為參數(shù):


并像這樣使用它:


export function t(key: string) {

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

  return useMemo(() => getDeepNestedFieldValue(locale+'.'+key,translations), [locale, translations, id]);

}

純 JS 中的示例:


const getDeepNestedFieldValue = (path, obj) => {

  return path.split('.').reduce((p, c) => (p && p[c]) || null, obj);

}

let user = {

  name: {

    first: 'John',

    last: 'Doe'

  },

  address: {

    city: {

      name: 'Cairo',

    }

  }

}



console.log(getDeepNestedFieldValue('name.first', user))

console.log(getDeepNestedFieldValue('address.city.name', user))


查看完整回答
反對 回復(fù) 2022-07-15
  • 1 回答
  • 0 關(guān)注
  • 137 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯(lián)系客服咨詢優(yōu)惠詳情

幫助反饋 APP下載

慕課網(wǎng)APP
您的移動學(xué)習(xí)伙伴

公眾號

掃描二維碼
關(guān)注慕課網(wǎng)微信公眾號