简体   繁体   中英

React Hook useEffect has a missing dependency: 'evaluate'. Either include it or remove the dependency array

How to add the code together in the useEffect? I cannot seem to find the solution.

const evaluate = () => {
     const [first, second] = openCards;
     enable();
     if (cards[first].type === cards[second].type) {
       setClearedCards((prev) => ({ ...prev, [cards[first].type]: true }));
       setOpenCards([]);
       return;
     }

To the useEffect:

useEffect(() => {
      console.log(openCards);
      let timeout = null;
      if (openCards.length === 2) {
        timeout = setTimeout(evaluate, 300);
      }
      return () => {
        clearTimeout(timeout);
      };
    }, [openCards]);

If you don't include it in the dependency array (second arg of useEffect ) it won't update when evaluate changes.

useEffect(() => {
      console.log(openCards);
      let timeout = null;
      if (openCards.length === 2) {
        timeout = setTimeout(evaluate, 300);
      }
      return () => {
        clearTimeout(timeout);
      };
    }, [openCards, evalute]); // Add it here

This is eslint warning, You can disable this

// eslint-disable-next-line react-hooks/exhaustive-deps
}, [openCards]);

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