简体   繁体   中英

Rerender a functional React component using useState and ensure useEffect hook executed

I have a functional React component which draws a polygon on a canvas. The result looks like this:

在此处输入图像描述

My code is (I have left out the irrelevant stuff):

import { useEffect, useState } from "react";

function Plot(props) {
  const [localPolygon, setlocalPolygon] = useState(props.polygon);

  useEffect(() => {
    // in here get the canvas context
    const { context } = getContext();
    // transforms data and draw the polygon on the canvas canvas
  }, [localPolygon]);

  const handleMouseMove = (event) => {
    // making some changes here to localPolgon as user drag
    // then update localPolygon
    setLocalPolygon(localPolygon);
    // I now expect the polygon to change position, but it does not
  };

  return (
    <>
      {" "}
      <canvas
        className="canvas"
        onMouseMove={(e) => {
          let nativeEvent = e.nativeEvent;
          handleMouseMove(nativeEvent);
        }}
      />
    </>
  );
}

export default Plot;

So the component loads, and in useEffect I do some transformation of data and draw it on the canvas. This works fine. I now want to drag the polygon. I'm able to get the new coordinates as I drag, and update localPolygon with setLocalPolygon(localPolygon) . I can see it getting updated, but the polygon is not changing position because the component does not seem to re-render - and useEffect is not called, which is what will update the canvas. You can see I have localPolygon as the second param in useEffect . Any ideas?

I don't know what type local polygon is, but I guess the problem is related to "shallow comparison"

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