简体   繁体   中英

React Hook useEffect has a missing dependency: 'loading'. Either include it or remove the dependency array react-hooks/exhaustive-deps

How can I fix this warning?

React Hook useEffect has a missing dependency: 'loading'. Either include it or remove the dependency array react-hooks/exhaustive-deps.

  useEffect(() => {
    if (!loading && data) {
      dispatch(action.TODO(data));
    }
  }, [data, dispatch]);

You add a dependency to a useEffect hook by specifying it in the second argument array.

Like this.

useEffect(() => {
  if (!loading && data) {
     dispatch(action.TODO(data));
  }
}, [data, dispatch, loading]);

The short answer is: in the array of the second parameter of useEffect remove dispatch and add loading

The correct answer is: When useEffect uses a variable as a conditional inside its execution, it considers it a dependency, and indicates that it should be executed again when it is being modified, otherwise it must be eliminated from the dependencies array

You are making use of useEffect and you are going to want to frequently refer to some variables declared as props or state inside of your component. You are already doing that with data . That is a piece of state that you are referring to inside your useEffect function.

loading is either a prop or a piece of state and when you are referring to a prop or a piece of state there is a rule written into ESLint specifically that wants you to reference any piece of prop or piece of state inside of useEffect dependency array. That controls when useEffect gets executed and that rule wants to see listed inside the dependency array the prop or piece of state you are referencing.

useEffect(() => {
  if (!loading && data) {
     dispatch(action.TODO(data));
  }
}, [data, dispatch, loading]);

Why does that rule want us to put that loading in there? There are some scenarios where making use of useEffect and not referencing the prop or piece of state inside the dependency can lead to some weird and hard to debug problems.

So that warning is all about helping you avoid hard to understand problems when making use of useEffect .

While that rule is well-intentioned, arbitrarily adding in so many rules to the dependency array can potentially lead to other bugs, just something to be aware of.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM