使用 useEffect 监听状态变化

Using useEffect for listening to state changes

我有以下 useEffect 挂钩:

useEffect(() => {
    let canvas = document.getElementById('canvas');
    if (canvas && image.img) {
      let context = canvas.getContext('2d');
      context.clearRect(0, 0, canvas.width, canvas.height);
      //Redraw image
      context.drawImage(image.img, 0, 0, image.width, image.height);
      let scalePoint1 = retrievePointByName(drawnPoints, 'S1');
      let scalePoint2 = retrievePointByName(drawnPoints, 'S2');
      if (scalePoint1 && scalePoint2) {
        let scaleLine = new Line(scalePoint1, scalePoint2, null, 'ScalePoint');
        setScaleProperties({
          scaleDistance: scaleLine.length(), //What is the distance between the scale points (in pixels)
          scaleValueMm: scaleProperties.scaleValueMm, //How many mm-s does the specified distance corresponds to
          scaleFactor:
            scaleProperties.scaleDistance / scaleProperties.scaleValueMm, //scaleDistance/scaleValueMm. Gives the factor, how many pixels are equal to 1 mm.
        });
        scaleLine.draw();
      }
      drawnPoints.forEach((point) => {
        point.draw();
      });
      setDrawnLines([]);
      setWrongPointPlacement({
        lines: [],
      });
    }
  }, [drawnPoints]);

但是,我收到以下警告:

“React Hook useEffect 缺少依赖项:'image.height'、'image.img'、'image.width'、'scaleProperties.scaleDistance' 和 'scaleProperties.scaleValueMm'。要么包含它们,要么删除依赖数组。

Image和scaleProperties也是组件的状态变量(用useState定义)

我觉得我可能在滥用 useEffect。我想的是将它用作“drawnPoints”状态更改的侦听器,以便在更新或更改点时重新绘制 canvas。 (并更新一些其他依赖状态)我正在处理一些可视化任务。

如果我确实滥用了这个概念,那么在 React 中实现这一点的“公认”或“最佳实践”方式是什么?

提前致谢!

useEffect 用法规则指出,每当您使用在 useEffect 钩子之外定义的 variable 时,您必须将其添加到 dependency array,因为 useEffect 依赖它并监听它的变化,每当它们的值发生变化时,它就必须 re-run.

在你的情况下,让我们考虑这行代码:

  //Redraw image
  context.drawImage(image.img, 0, 0, image.width, image.height);

您收到此警告的原因是,在您 redrawing 圆圈所在的线上,您告诉 useEffectimage.height,image.img,image.width 更改时始终重新绘制图像.正如我所说,这是因为 image.height,image.img,image.width 是在 useEffect 钩子之外定义的。