这个问题与eslint-plugin-react-hooks
有关。
当我在CodeSanbox中使用React时,我可以使用props对象的单个属性作为useEffect钩子的依赖项:
示例1:
useEffect(()=>{
console.log('Running useEffect...');
console.log(typeof(props.myProp)); // USING ONLY 'myProp' PROPERTY
},[ ]); // EMPTY ARRAY
示例1给出了以下警告在CodeSandbox环境中:
React缺少一个依赖项:‘pros.myprop’。要么包含它,要么删除依赖数组。(反应-钩/详尽-)
如果我将[props.myProp]
添加到数组中,警告就会消失。
但是,在VSCode的本地环境中,同样的示例1,我得到了下面的警告
React缺少一个依赖项:“props”。要么包含它,要么删除依赖数组。但是,当任何道具发生变化时,“props”都会发生变化,因此首选的修复方法是在useEffect调用之外分解“props”对象,并引用useEffect.eslint中的那些特定道具(react钩子/详尽-deps)。
是问我错过了完整的props
对象。如果我将[props.myProp]
添加到数组中,则警告不会消失。,尽管代码按预期工作。
我希望在VSCode的本地环境中,我会得到与VSCode上相同的行为。
会发生什么事?我可以在eslint-plugin-react-hooks
中更改任何配置吗?
包
发展:
"eslint": "^5.10.0",
"eslint-plugin-react": "^7.11.1",
"eslint-plugin-react-hooks": "^1.6.1",
规则性
"react": "^16.8.6",
"react-dom": "^16.8.6",
.eslintrc.json
{
"root" :true,
"env": {
"browser": true,
"commonjs": true,
"es6": true,
"node": true
},
"extends": [
"eslint:recommended",
"plugin:react/recommended",
"plugin:import/errors"
],
"parser":"babel-eslint",
"parserOptions": {
"ecmaVersion": 8,
"sourceType": "module",
"ecmaFeatures": {
"jsx":true
}
},
"plugins":[
"react",
"react-hooks"
],
"rules": {
"react/prop-types": 0,
"semi": "error",
"no-console": 0,
"react-hooks/rules-of-hooks": "error",
"react-hooks/exhaustive-deps": "warn"
},
"settings": {
"import/resolver" : {
"alias" : {
"map" : [
["@components","./src/components"],
["@constants","./src/constants"],
["@helpers","./src/helpers"]
],
"extensions": [".js"]
}
}
}
}
发布于 2020-04-24 15:49:27
这个问题的答案在这里得到了一定的回答:https://github.com/facebook/react/issues/16265#issuecomment-517518539
插件之所以对它有不同的看法,是因为通过执行
props.whatever()
,您实际上是将props
本身作为this
值传递给whatever
。所以从技术上讲,它会看到过时的道具。 通过在调用之前读取函数,您将避免这个问题。
虽然答案是毁灭是答案,但有一个小小的警告。解构或重新分配除了解决警告(99%的情况)之外没有任何效果,或者破坏您的代码。如果您重构或重新分配,该函数将没有this
,如果这不是问题,那么警告就没有意义了。这是一个设计的案例的演示,其中任何一个都是重要的。
function bark() {
console.log(`${this.name} barked.`);
}
const mac = {
name: "mac",
bark
};
const cheese = {
name: "cheese",
bark
};
const DogBark = props => {
useEffect(() => props.dog.bark(), [props.dog.bark]);
return null;
};
const Dog = () => {
const [dog, setDog] = React.useState(mac);
useEffect(() => setDog(cheese), []);
// will cheese bark?
return (
<DogBark dog={dog} />
);
};
奶酪是不会叫的。当您开始使用useCallback
时,问题变得更严重了
const DogBarkByCallback = props => {
const bark = React.useCallback(() => props.dog.bark(), [props.dog.bark]);
// every dog should bark, and if the definition of
// bark changes even though the dog is the same, it should bark again
useEffect(() => bark(), [props.dog, bark]);
return null;
};
在这种情况下,mac会吠叫两次,因为回调不会改变。因此,解决方案要么是确保[props.dog]
在您的依赖数组中(正如警告所建议的那样),要么是知道您不需要this
并重构或重新分配值以规避警告。
https://stackoverflow.com/questions/57289668
复制相似问题