[英]How to fix eslint warning warning JSX attribute values should not contain functions created in the same scope react-perf/jsx-no-new-function-as-prop
i am new to programming and learning typescript and i have been trying to understand and fix the eslint warning.我是编程和学习 typescript 的新手,我一直在尝试理解和修复 eslint 警告。 i have code like below,
我有如下代码,
const handleRequestDelete = async () => { //eslint warning
try {
await deleteSomething({ variables: { ids }});
onSuccess();
} catch (error) {
const [{ status, title, description }] =
apolloErrorToNotifications(error);
onError(error);
throw error;
}
};
on line const handleRequestDelete it throws eslint warning like so.在线 const handleRequestDelete 它会像这样抛出 eslint 警告。
warning JSX attribute values should not contain functions created in the same scope react-perf/jsx-no-new-function-as-prop
how could i fix this error.我该如何解决这个错误。 could someone help me.
有人可以帮助我吗? thanks.
谢谢。
That lint rule is pointing out that handleRequestDelete
will be created new on every render.该 lint 规则指出,将在每次渲染时创建新的
handleRequestDelete
。 To satisfy the lint rule, you'll need to wrap your function in useCallback
:为了满足 lint 规则,您需要将 function 包装在
useCallback
中:
const handleRequestDelete = useCallback(
async () => {
try {
await deleteSomething({ variables: { ids } });
onSuccess();
} catch (error) {
const [{ status, title, description }] =
apolloErrorToNotifications(error);
onError(error);
throw error;
}
},
[/* insert dependencies here */]
);
By doing this, then as long as the dependency array doesn't change, you'll reuse the same function on each render.通过这样做,只要依赖数组不改变,您将在每次渲染时重用相同的 function。 I'm not exactly sure what the dependency array needs to contain, but my guess is
[deleteSomething, onSuccess, apolloErrorToNotifications, onError]
我不确定依赖数组需要包含什么,但我的猜测是
[deleteSomething, onSuccess, apolloErrorToNotifications, onError]
If you don't find this lint rule useful, you can disable it in your .eslint.json
file, by adding this to the rules section:如果您觉得这条 lint 规则没有用,您可以在
.eslint.json
文件中禁用它,方法是将其添加到规则部分:
"rules": {
"react-perf/jsx-no-new-function-as-prop": "off"
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.