gpt4 book ai didi

reactjs - 为 React 组件中未使用的类方法设置 eslint 规则

转载 作者:行者123 更新时间:2023-12-03 13:38:21 25 4
gpt4 key购买 nike

我正在尝试为类中从未使用过的方法设置 eslint 规则。就像在下面的 React 组件中一样,我有一个从未使用过的方法 unUsedMethod ,但 eslint 不会显示它的错误。

class Sample extends Component {
unUsedMethod() {
console.log('I am never used');
}
render() {
return 'Hello!';
}
}

我的 eslint 文件看起来像这样

{
"parser": "babel-eslint",
"env": {
"browser": true,
"es6": true,
"node": true
},
"extends": ["eslint:recommended", "plugin:react/recommended"],
"parserOptions": {
"ecmaFeatures": {
"experimentalObjectRestSpread": true,
"jsx": true,
"sourceType": "module",
"allowImportExportEverywhere": false,
"codeFrame": false
},
"sourceType": "module"
},
"plugins": [
"react"
],
"rules": {
"indent": [2, 4, {"SwitchCase": 1, "ObjectExpression": "first"}],
"linebreak-style": [
"error",
"unix"
],
"semi": [
"error",
"always"
],
"react/display-name": 0,
"react/prop-types": 0, // Temporary
"react/no-unescaped-entities": 0,
"no-trailing-spaces": 1
}
}

最佳答案

这个插件可以满足您的要求。不过请注意。

https://www.npmjs.com/package/eslint-plugin-no-unused-react-component-methods

目前不可能简单地有一个解析器来检查未使用的组件属性,因为组件属性可以动态调用。

例如:

class Sample extends Component {
// Plugin falsely flags this as unused.
unUsedMethod() {
console.log('I am used dynamically');
}
render() {
// No way to parse dynamic function calls reliably
this['unUsedMethod']();
return 'Hello!';
}
}

它也不适用于react-onclickoutside包,因为它需要将一个函数附加到组件,通过将组件包装在HOC中来调用该函数。 https://www.npmjs.com/package/react-onclickoutside

该插件仍然帮助我找到了一些未使用的功能,所以我认为它值得一试。

首先安装软件包:npm i eslint-plugin-no-unused-react-component-methods --save-dev

将“no-unused-react-component-methods”添加到插件部分的 eslint 配置中:

{
"plugins": [
"no-unused-react-component-methods"
],
}

并添加到规则部分

{
"rules": {
"no-unused-react-component-methods/no-unused-react-component-methods": 2,
}
}

所以你的配置看起来像:

{
"parser": "babel-eslint",
"env": {
"browser": true,
"es6": true,
"node": true
},
"extends": ["eslint:recommended", "plugin:react/recommended"],
"parserOptions": {
"ecmaFeatures": {
"experimentalObjectRestSpread": true,
"jsx": true,
"sourceType": "module",
"allowImportExportEverywhere": false,
"codeFrame": false
},
"sourceType": "module"
},
"plugins": [
"react",
"no-unused-react-component-methods"
],
"rules": {
"no-unused-react-component-methods/no-unused-react-component-methods": 2,
"indent": [2, 4, { "SwitchCase": 1, "ObjectExpression": "first" }],
"linebreak-style": ["error", "unix"],
"semi": ["error", "always"],
"react/display-name": 0,
"react/prop-types": 0, // Temporary
"react/no-unescaped-entities": 0,
"no-trailing-spaces": 1
}
}

现在它应该突出显示任何看似未使用的功能!让我知道它是否有效。

关于reactjs - 为 React 组件中未使用的类方法设置 eslint 规则,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46584642/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com