reactjs - React Hook useEffect 缺少依赖项 : 'colors' and 'options' . 包括它们或删除依赖项数组

标签 reactjs

我正在尝试在发布和运行 React Hook 错误之前进行我的第一个 React 构建,如下所示: “React Hook useEffect 缺少依赖项:'colors' 和 'options'。要么包含它们,要么删除依赖项数组。

我的组件在最后一行显示错误。我做错了什么?

function MemoryGame({ options, setOptions, highScore, setHighScore }) {
  const [game, setGame] = useState([]);
  const [flippedCount, setFlippedCount] = useState(0);
  const [flippedIndexes, setFlippedIndexes] = useState([]);

  const colors = [
    `url(${Background1})`,
    `url(${Background13})`,
    `url(${Background3})`,
    `url(${Background4})`,
    `url(${Background5})`,
    `url(${Background6})`,
    `url(${Background7})`,
    `url(${Background8})`,
    `url(${Background9})`,
    `url(${Background14})`,
    `url(${Background11})`,
    `url(${Background12})`,
  ];

  useEffect(() => {
    const newGame = [];
    for (let i = 0; i < options / 2; i++) {
      const firstOption = {
        id: 2 * i,
        colorId: i,
        color: colors[i],
        flipped: false,
      };
      const secondOption = {
        id: 2 * i + 1,
        colorId: i,
        color: colors[i],
        flipped: false,
      };

      newGame.push(firstOption);
      newGame.push(secondOption);
    }

    const shuffledGame = newGame.sort(() => Math.random() - 0.5);
    setGame(shuffledGame);
  }, []);

我刚刚添加了 [colors, options] 但现在我得到了这个: 'colors' 数组使 useEffect Hook 的依赖项(第 137 行)在每次渲染时都会发生变化。将它移到 useEffect 回调中。或者,将 'colors' 的初始化包装在它自己的 useMemo() Hook 中。

现在我尝试在 useEffect 中移动 const colors 并且变得未定义。我还做错了什么?

  useEffect(() => {
    const colors = [
      `url(${Background1})`,
      `url(${Background13})`,
      `url(${Background3})`,
      `url(${Background4})`,
      `url(${Background5})`,
      `url(${Background6})`,
      `url(${Background7})`,
      `url(${Background8})`,
      `url(${Background9})`,
      `url(${Background14})`,
      `url(${Background11})`,
      `url(${Background12})`,
    ];
    const newGame = [];
    for (let i = 0; i < options / 2; i++) {
      const firstOption = {
        id: 2 * i,
        colorId: i,
        color: colors[i],
        flipped: false,
      };
      const secondOption = {
        id: 2 * i + 1,
        colorId: i,
        color: colors[i],
        flipped: false,
      };
      newGame.push(firstOption);
      newGame.push(secondOption);
    }
    const shuffledGame = newGame.sort(() => Math.random() - 0.5);
    setGame(shuffledGame);
  }, [colors, options]);

最佳答案

不要忽视警告,它的存​​在是有充分理由的。它的目的是通知您,您正在使用对在钩子(Hook)本身之外定义的变量的引用,这些变量可能会发生变异并使您处于陈旧状态。

useEffect 钩子(Hook)接受 2 个参数,其中第二个是一个依赖项数组 - 在您的例子中是一个空的。基于此数组,React 知道何时应执行 useEffect 中的回调。在你的情况下提供一个空数组将导致回调只运行一次,在组件的初始渲染之后并且不会再运行,无论你的组件发生什么变化。因此,即使您更改了 colorsoptions 引用, Hook 也不会执行,您将处于陈旧状态,因此会出现警告。但是,您的代码实际上依赖于这两个引用,因此您应该将它们放在依赖数组中,以指示 react 在它们中的任何一个发生变化时重新运行回调函数(即使它们是常量并且您知道不会改变) .所以,使用这个:

  useEffect(() => {
    const newGame = [];
    for (let i = 0; i < options / 2; i++) {
      const firstOption = {
        id: 2 * i,
        colorId: i,
        color: colors[i],
        flipped: false,
      };
      const secondOption = {
        id: 2 * i + 1,
        colorId: i,
        color: colors[i],
        flipped: false,
      };

      newGame.push(firstOption);
      newGame.push(secondOption);
    }

    const shuffledGame = newGame.sort(() => Math.random() - 0.5);
    setGame(shuffledGame);
  }, [colors, options]);

基本上,如果一个变量(包括函数)只在 useEffect 回调中使用,你应该在里面定义它,你可以跳过将它添加到依赖数组,因为它可以在内部跟踪它。 在极少数情况下,当您仅依赖于 useEffect 的变量的初始状态(可以在之后发生变异)并且您只想在组件“setup”上运行一次 Hook 时,您应该跳过添加它到依赖数组,它不会导致它重新执行。

关于reactjs - React Hook useEffect 缺少依赖项 : 'colors' and 'options' . 包括它们或删除依赖项数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/66017049/

相关文章:

javascript - React select onChange 不使用选项值

javascript - Firebase 监听器或下拉刷新

node.js - React Router 与生产中的路径 = "/"不匹配

javascript - 为什么通过 props 正确传递的数组返回未定义?

javascript - 在哪里初始化 API key (例如 : Amplitude) in a React Native App (with Expo + Redux)?

reactjs - 如何为 Material UI 的 TableHead 赋予圆角

node.js - `npx create-react-app` 说它需要 "Node 14 or higher"但我运行的是 17.4.0。我怎样才能解决这个问题?

javascript - Meteor 尚不支持 ECMA7 静态原型(prototype),有什么好的解决方法吗?

javascript - React Router Props 未定义

javascript - 动态更新 MapView.UrlTile 组件的 urlTemplate 属性