如何修复ESLint警告:JSX属性值勿含同作用域创建的函数
修复
react-perf/jsx-no-new-function-as-prop ESLint警告 这个警告的核心原因是:你把当前组件作用域里创建的handleRequestDelete函数直接作为JSX属性(比如onClick)传给了子组件。每次父组件渲染时,都会生成一个新的handleRequestDelete函数实例,这不仅会浪费性能,还可能导致子组件不必要的重渲染。
修复方案分两种情况:
情况1:你用的是React函数组件
用useCallback钩子缓存函数实例,只有当依赖的变量变化时才重新创建函数:
import { useCallback } from 'react'; // 在组件内部定义 const handleRequestDelete = useCallback(async () => { try { await deleteSomething({ variables: { ids }}); onSuccess(); } catch (error) { const [{ status, title, description }] = apolloErrorToNotifications(error); onError(error); throw error; } }, [ids, deleteSomething, onSuccess, onError]); // 把函数里用到的所有外部变量/函数都放进依赖数组
注意:如果deleteSomething、onSuccess、onError是父组件传过来的props,要确保父组件也用useCallback(或useMemo)缓存了这些函数,否则子组件的useCallback还是会频繁更新。
情况2:你用的是React类组件
把handleRequestDelete定义为类的实例方法,而不是在render函数里创建:
class YourComponent extends React.Component { // 用箭头函数自动绑定this,避免手动bind handleRequestDelete = async () => { try { await deleteSomething({ variables: { ids: this.props.ids }}); this.props.onSuccess(); } catch (error) { const [{ status, title, description }] = apolloErrorToNotifications(error); this.props.onError(error); throw error; } }; render() { // 直接传类方法的引用,每次render都是同一个实例 return <Button onClick={this.handleRequestDelete} />; } }
这样每次渲染时传给子组件的都是同一个函数引用,就不会触发ESLint警告了。
内容的提问来源于stack exchange,提问作者user19725419
相关产品推荐
相关产品推荐

