这个问题与 eslint-plugin-react-hooks
当我使用React Sandbox中的Codesanbox时,我可以使用Props对象的单个属性作为使用效果钩的依赖项:
示例1:
useEffect(()=>{
console.log('Running useEffect...');
console.log(typeof(props.myProp)); // USING ONLY 'myProp' PROPERTY
},[ ]); // EMPTY ARRAY
示例1在代码框环境中给我以下警告:
react hook useffect缺少依赖性:" props.myprop"。包括它或删除依赖关系数组。(反应钩/详尽的deps(eslint
,如果我将 [props.myProp]
添加到数组中,警告就会消失。
但是在我本地环境中的Vscode中的同一示例1,我得到以下警告:
React Hook使用效应缺少依赖性:" Props"。包括它或删除依赖关系数组。但是,当任何道具更改时,"道具"将会发生变化,因此首选的修复程序是破坏使用效率调用之外的" props"对象,并在useeffect.eslint(react-hooks/afterive-deps(内参考那些特定的道具
问我我缺少完整的props
对象。如果我将 [props.myProp]
添加到数组中,警告不会消失。尽管代码按预期工作。
我希望我会在VSCODE的本地环境中获得与我在codesandbox上获得的相同行为。
会发生什么?我可以在eslint-plugin-react-hooks
中更改任何配置吗?
软件包
dev:
"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"]
}
}
}
}
这个问题的答案在这里有点回答:https://github.com/facebook/react/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://codesandbox.io/s/exhaustive-deps-fn-mrdld