繁体   English   中英

React Hook useEffect 缺少依赖项:'evaluate'。 包括它或删除依赖数组

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

如何在useEffect中将代码一起添加? 我似乎找不到解决方案。

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

对使用效果:

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

如果您没有将它包含在依赖数组中( useEffect的第二个参数),它在评估更改时不会更新。

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

这是 eslint 警告,您可以禁用它

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

暂无
暂无

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

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