我有一个小的本地化提供程序库,该库调用服务器以根据用户选择的语言获得翻译。为了简洁起见,我省略了一些辅助函数。这是要点:
const LocaleContext = createContext();
const LocaleProvider = ({ children }) => {
const [state, setState] = useState(defaultValues);
if (state.phrases === null) {
changeLanguage(defaultLanguage);
}
return (
<LocaleContext.Provider value={[state, setState]}>
{children}
</LocaleContext.Provider>
);
};
const changeLanguage = (lang) => {
const [state, setState] = useContext(LocaleContext);
fetch(localizationEndpointForThatLanguage)
.then(response => response.json())
.then(data => {
setState({ ...state, phrases: data });
};
const translateString = (string) => {
const [state] = useContext(LocaleContext);
// if the string argument is found in state, return the translated value;
}
export { LocaleContext, LocaleProvider, changeLanguage, translateString };
以下是使用它的组件:
const Home = () => {
const [state, setState] = useContext(SiteContext);
useEffect(() => {
state.fetchContent(opts, state, setState);
}, []);
return (
<div>
{state.data && state.data.map((datum) => <div>{datum.title}</div>)}
<div onClick={() => changeLanguage('pl_PL')}>Change to Polish</div>
<div>{changeLanguage('Translate me')}</div>
</div>
);
};
当尝试在changeLanguage函数中分解LocaleContext时,代码给我错误“ TypeError:无法读取未定义的属性'0'”。它适用于translateString函数。如果我将状态手动传递到changeLanguage函数中,它将起作用。
const Home = () => {
const [state, setState] = useContext(SiteContext);
const [locale, setLocale] = useContext(LocaleContext);
useEffect(() => {
state.fetchContent(opts, state, setState);
}, []);
return (
<div>
{state.data && state.data.map((datum) => <div>{datum.title}</div>)}
<div onClick={() => changeLanguage('pl_PL')}>Change to Polish</div>
<div>{changeLanguage('Translate me', locale, setLocale)}</div>
</div>
);
};
和
const changeLanguage = (lang, state, setState) => {
fetch(localizationEndpointForThatLanguage)
.then(response => response.json())
.then(data => {
setState({ ...state, phrases: data });
});
};
我必须在整个应用程序中传递上下文值才能使工作正常。我想帮助您理解为什么我的translateString函数不需要我将上下文值传递给它。