[英]React Hook "useForecast" is called in function "getSearch" that is neither a React function component nor a custom React Hook function
[英]React Hook "useTranslation" is called in function "getMyMenu" that is neither a React function component nor a custom React Hook function
我正在從正常的 function 中調用useTranslation
掛鈎,如下所示
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
鈎子移動到MyNav
組件主體並將翻譯 function 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);
...
}
我剛剛更新了我的
recurseFn
樣子。 是否可以將“t”傳遞給它?
t
顯式傳遞給所有函數 You could certainly update the function signature of recurseFn
to also consume a "t" (translation?) function, but you'd still need to then also pass t
into chk
which would necessitate updating the original getMyMenu
function to consume an additional argument.
例子:
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
...
}
在這種情況下,我認為將getMyMenu
設置為 curried function 可以幫助您將t
包含在回調中,並允許在任何 React 組件外部聲明它。 recurseFn
function 不需要知道任何關於t
的信息,所以為什么要在那里公開它,對吧?
const getMyMenu = t => a => {
if (a.showRoute) {
a.label = t(a.label);
return a;
}
}
現在你從useTranslation
鈎子返回值中解構t
並傳遞給getMyMenu
function。 這與在回調中關閉t
function 的想法類似,就像我們在第一個答案中所做的那樣。
import { useTranslation } from "react-i18next";
export const MyNav = props => {
const { t } = useTranslation('translations');
let tabs = recurseFn(getMyMenu(t), props.routes);
...
}
現在從recurseFn
的角度來看, t
包含在chk
回調中,並且recurseFn
不需要顯式處理接收和傳遞t
。
通過確保 function 名稱大寫,我能夠解決同樣的問題。 投訴明確指出“React 組件名稱必須以大寫字母開頭”。 更正此問題后,ESLint 消息消失了。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.