使用 useEffect 监听状态变化

时间:2021-03-18 20:44:54

标签: javascript reactjs react-hooks use-effect react-component

我有以下 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”状态更改的侦听器,以便在更新或更改点时,我重新绘制画布。 (并更新其他一些依赖状态)我正在处理一些可视化任务。

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

先谢谢你!

1 个答案:

答案 0 :(得分:0)

useEffect 使用规则表示,每当您使用在 variable 钩子之外定义的 useEffect 时,您都必须将其添加到 dependency array,因为 {{1} } 依赖于它并倾听它的变化,每当它们的值发生变化时,它就必须useEffect

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

re-run

您收到此警告的原因是,在您是 //Redraw image context.drawImage(image.img, 0, 0, image.width, image.height); 圆圈的那一行上,您告诉 redrawinguseEffect 更改时始终重新绘制图像。正如我所说,这样做的原因是因为 image.height,image.img,image.width 是在 image.height,image.img,image.width 钩子之外定义的。