简体   繁体   English

'exhaustive-deps' 的警告不断要求完整的 'props' 对象,而不是允许单个 'props' 方法作为依赖项

[英]Warning for 'exhaustive-deps' keeps asking for the full 'props' object instead of allowing single 'props' methods as dependencies

This question is related to the eslint-plugin-react-hooks这个问题与eslint-plugin-react-hooks

When I'm in CodeSanbox using a React Sandbox I can use single properties of the props object as dependencies for the useEffect hook:当我在 CodeSanbox 中使用 React Sandbox 时,我可以使用 props 对象的单个属性作为 useEffect 钩子的依赖项:

Example 1:示例 1:

useEffect(()=>{
  console.log('Running useEffect...');
  console.log(typeof(props.myProp));    // USING ONLY 'myProp' PROPERTY
},[ ]);                                 // EMPTY ARRAY

The example 1 gives me the following warning in CodeSandbox environment:示例 1 在 CodeSandbox 环境中给了我以下警告

React Hook useEffect has a missing dependency: 'props.myProp'. React Hook useEffect 缺少依赖项:'props.myProp'。 Either include it or remove the dependency array.包括它或删除依赖项数组。 (react-hooks/exhaustive-deps) eslint (react-hooks/exhaustive-deps) eslint

And if I add [props.myProp] to the array, the warning goes away.如果我将[props.myProp]添加到数组中,警告就会消失。

But the same example 1 in my local environment in VSCode, I get the following warning :但是在我的 VSCode 本地环境中的相同示例 1,我收到以下警告

React Hook useEffect has a missing dependency: 'props'. React Hook useEffect 缺少一个依赖项:'props'。 Either include it or remove the dependency array.包括它或删除依赖项数组。 However, 'props' will change when any prop changes, so the preferred fix is to destructure the 'props' object outside of the useEffect call and refer to those specific props inside useEffect.eslint(react-hooks/exhaustive-deps)然而,'props' 会在任何 props 改变时改变,所以首选的解决方法是在 useEffect 调用之外解构 'props' 对象,并在 useEffect.eslint(react-hooks/exhaustive-deps) 中引用那些特定的 props

Is asks me that I'm missing the full props object.是问我缺少完整的props对象。 And if I add [props.myProp] to the array, the warning DOES NOT go away.如果我将[props.myProp]添加到数组中,警告不会消失。 Although the code works as intended.尽管代码按预期工作。

I would expect that I would get the same behavior that I get on CodeSandbox in my local environment in VSCode.我希望我会在 VSCode 的本地环境中获得与在 CodeSandbox 上获得的行为相同的行为。

What could be happening?会发生什么? Is there any configuration I could change in eslint-plugin-react-hooks ?我可以在eslint-plugin-react-hooks更改任何配置吗?

PACKAGES套餐

DEV:开发:

"eslint": "^5.10.0",
"eslint-plugin-react": "^7.11.1",
"eslint-plugin-react-hooks": "^1.6.1",

REGULAR常规的

"react": "^16.8.6",
"react-dom": "^16.8.6",

.eslintrc.json .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"]
      }
    }
  }
}

The answer to this question is somewhat answered here: https://github.com/facebook/react/issues/16265#issuecomment-517518539这个问题的答案在这里有些回答: https : //github.com/facebook/react/issues/16265#issuecomment-517518539

The reason plugin sees it differently is because by doing props.whatever() you are actually passing props itself as a this value to whatever .该插件之所以看到它不同是因为这样做props.whatever()你实际上是通过props本身作为thiswhatever So technically it would see stale props.所以从技术上讲,它会看到陈旧的道具。

By reading the function before the call you're avoiding the problem.通过在调用之前读取函数,您可以避免这个问题。

Although the answer says that destructuring is the answer, there is a small caveat.虽然答案说解构就是答案,但有一个小小的警告。 Destructuring or reassigning will either have no effect except resolving the warning (99% of cases) or break your code.除了解决警告(99% 的情况)或破坏您的代码之外,解构或重新分配将没有任何效果。 If you destructure or reassign, the function will have no this , and if that's not a problem then the warning was meaningless.如果您解构或重新分配,该函数将没有this ,如果这不是问题,则警告毫无意义。 Here's a demo of a contrived case where any of this matters.这是一个人为案例的演示,其中任何一个都很重要。

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} />
  );
};

Cheese will not bark.奶酪不会吠叫。 The problem becomes worse when you start using useCallback :当您开始使用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;
};

In this case, mac barks twice because the callback doesn't change.在这种情况下,mac 吠叫两次,因为回调没有改变。 Thus, the solution is either to make sure [props.dog] is in your dependency array, as the warning recommends, or to know you don't need this and destructure or reassign the value to circumvent the warning.因此,解决方案是确保[props.dog]位于您的依赖项数组中,正如警告所建议的那样,或者知道您不需要this并解构或重新分配值以规避警告。

Demonstrated here in the console: https://codesandbox.io/s/exhaustive-deps-fn-mrdld在控制台中演示: https : //codesandbox.io/s/exhaustive-deps-fn-mrdld

Did you considered destructuring the property? 您是否考虑过破坏财产?

const { myProp } = props
useEffect(()=>{
  console.log('Running useEffect...');
  console.log(typeof(myProp));    // USING ONLY 'myProp' PROPERTY
},[myProp]);  

I understood what was going on. 我了解发生了什么事。 It's not a bug (I think). 这不是一个错误(我认为)。

This code: 这段代码:

useEffect(()=>{
  function someFunction() {
    props.whatever();                  // CALLING A FUNCTION FROM PROPS
  }
},[ ]);

Results in this warning: 结果如下:

React Hook useEffect has a missing dependency: 'props'. React Hook useEffect缺少依赖项:“ props”。 Either include it or remove the dependency array. 包括它或删除依赖项数组。 However, 'props' will change when any prop changes, so the preferred fix is to destructure the 'props' object outside of the useEffect call and refer to those specific props inside useEffect. 但是,“ props”将在任何 prop发生更改时发生更改,因此首选解决方法是在useEffect调用之外对“ props”对象进行解构,并引用useEffect内部的那些特定prop。 (react-hooks/exhaustive-deps)eslint (反应钩/穷举)


And this code: 这段代码:

useEffect(()=>{
  function someFunction() {
    props.whatever;                          // ACCESSING A PROPERTY FROM PROPS
  }
},[]);

Results in this warning: 结果如下:

React Hook useEffect has a missing dependency: 'props.whatever'. React Hook useEffect缺少依赖项:“ props.whatever”。 Either include it or remove the dependency array. 包括它或删除依赖项数组。 (react-hooks/exhaustive-deps)eslint (反应钩/穷举)


I'm not sure why, but the plugin see it differently when you're calling a method from props or if your acessing a property from props . 我不确定为什么,但是当您从props调用方法或从props property时,插件对它的看法有所不同。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 使用 eslint Exclusive-deps 响应订阅/取消订阅的 useEffect 依赖项 - React useEffect dependencies for subscribe/unsubscribe with eslint exhaustive-deps 带有自定义 IntersectionObserver 钩子的 react-hooks/exhaustive-deps 警告 - react-hooks/exhaustive-deps warning with custom IntersectionObserver hook 反应 useEffect 带有警告的钩子 react-hooks/exhaustive-deps - React useEffect hook with warning react-hooks/exhaustive-deps 设计React Hooks可以防止React-Hooks / Exhaustive-deps警告 - Designing React Hooks prevent react-hooks/exhaustive-deps warning react-hooks/exhaustive-deps 导致依赖警告,修复挂起代码 - react-hooks/exhaustive-deps causing dependency warning, fix hangs code React Hook useEffect 缺少依赖项:“roomID”和“sotreId”。 要么包含它们,要么删除依赖数组 react-hooks/exhaustive-deps - React Hook useEffect has missing dependencies: 'roomID 'and 'sotreId'. Either include them or remove the dependency array react-hooks/exhaustive-deps useEffect 和 &#39;react-hooks/exhaustive-deps&#39; linting - useEffect and 'react-hooks/exhaustive-deps' linting 有没有办法记住从 params 传递过来的函数 - (useCallback)exhaustive-deps - Is there a way to memoize a function passed from params - (useCallback) exhaustive-deps 未找到规则“re​​act-hooks/exhaustive-deps”的定义 - Definition for rule 'react-hooks/exhaustive-deps' was not found props 作为字符串返回,而不是 object - props are returned as string instead of object
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM