1 回答

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))
添加回答
舉報