我正在从一个普通函数中调用 useTranslation
Hook ,如下所示
import { useTranslation } from "react-i18next";
function getMyMenu(a) {
const { t } = useTranslation('translations');
if (a.showRoute) {
a.label = t(a.label);
return a;
}
}
export const MyNav = props => {
let tabs = recurseFn(getMyMenu, props.routes);
}
我收到以下错误。没有办法解决这个问题吗?出于某种奇怪的原因,我能够在其他项目中看到类似的代码模式。需要任何其他配置才能使这项工作正常进行吗?
更新:
这就是我的 recurseFn
的样子:
export const recurseFn = (chk, [head, ...tail]) => {
if (head === undefined) return [];
if (chk(head)) {
return [head, ...recurseFn(chk, tail)];
}
return [...recurseFn(chk, tail)];
};
最佳答案
您可以通过将 useTranslation
Hook 移动到 MyNav
组件主体并将翻译函数 t
作为 中的闭包来修复它>getMyMenu
.
import { useTranslation } from "react-i18next";
export const MyNav = props => {
const { t } = useTranslation('translations');
function getMyMenu(a) {
if (a.showRoute) {
a.label = t(a.label);
return a;
}
}
let tabs = recurseFn(getMyMenu, props.routes);
...
}
编辑
I just updated with how my
recurseFn
looks like. Is it possible to pass "t" to it?
解决方案 1 - 将 t
显式传递给所有函数
您当然可以更新 recurseFn
的函数签名以也使用“t”(翻译?)函数,但您仍然需要传递 t
进入 chk
,这将需要更新原始 getMyMenu
函数以使用额外的参数。
例子:
function getMyMenu(t, a) { // <-- consume additional t argument
if (a.showRoute) {
a.label = t(a.label);
return a;
}
}
...
export const recurseFn = (chk, [head, ...tail], t) => { // <-- consume additional t argument
if (head === undefined) return [];
if (chk(t, head)) { // <-- pass t to chk
return [head, ...recurseFn(chk, tail, t)]; // <-- pass t on recursion
}
return [...recurseFn(chk, tail, t)]; // <-- pass t on recursion
};
...
import { useTranslation } from "react-i18next";
export const MyNav = props => {
const { t } = useTranslation('translations');
let tabs = recurseFn(getMyMenu, props.routes, t); // <-- pass t on recursion
...
}
解决方案 2 - 使用柯里化(Currying)回调的更好解决方案
在这种情况下,我认为使 getMyMenu
成为柯里化(Currying)函数可以帮助您将 t
包含在回调中,并允许它在任何 React 组件的外部声明。 recurseFn
函数不需要知道关于 t
的任何信息,所以为什么要把它公开在那里,对吧?
const getMyMenu = t => a => {
if (a.showRoute) {
a.label = t(a.label);
return a;
}
}
现在您从 useTranslation
钩子(Hook)返回值中解构 t
并传递给柯里化(Currying)的 getMyMenu
函数。这与我们在第一个答案中所做的回调中关闭 t
函数的想法类似。
import { useTranslation } from "react-i18next";
export const MyNav = props => {
const { t } = useTranslation('translations');
let tabs = recurseFn(getMyMenu(t), props.routes);
...
}
现在从 recurseFn
的 Angular 来看,t
包含在 chk
回调中而 recurseFn
没有需要显式处理接收和传递 t
。
关于javascript - React Hook "useTranslation"在既不是 React 函数组件也不是自定义 React Hook 函数的函数 "getMyMenu"中被调用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/66849844/