解决:React Hook useEffect-重新渲染/重置问题

时间:2020-10-02 07:41:51

标签: reactjs dependencies react-hooks use-effect

我正在尝试创建一个重置按钮,该按钮会更改useEffect中的依赖项值。 我认为这将重新渲染组件,从而将所有值设置为代码中所示的默认值。

 const TransformedDoor = ({ doorHook }) => {
  const { selectedDoor } = doorHook;
  const [ doorWidth, setDoorWidth ] = useState(0);
  const [ doorHeight, setDoorHeight] = useState(0);
  const [ reset, doReset ] = useState(0);

  const DEFAULT_MATRIX = [1.0,0.0,0.0,0.0,0.0,1.0,0.0,0.0,0.0,0.0,1.0,0.0,0.0,0.0,0.0,1.0];
  const [ transformationMatrix, setTransformationMatrix] = useState(DEFAULT_MATRIX);
  const [ doorOffset, setDoorOffset ] = useState({x: 300,y: 200});
  const [ mouseState, setMouseState ] = useState({targetCircle: -1});
  const [ corners, setCorners ] = useState(
    {
     0: {x: 0, y: 0},
     1: {x: doorWidth, y: 0},
     2: {x: doorWidth, y: doorHeight},
     3: {x: 0, y: doorHeight},
    }
  );

  useEffect(() => {
    const { width, height } = selectedDoor;
    const scaler = 200 / Math.max(width, height);
    const w = width * scaler;
    const h = height * scaler;
    if (w !== doorWidth || h !== doorHeight) {
      setDoorWidth(w);
      setDoorHeight(h);
      setCorners({
        0: {x: 0, y: 0},
        1: {x: w, y: 0},
        2: {x: w, y: h},
        3: {x: 0, y: h},
      });
      setTransformationMatrix(DEFAULT_MATRIX);
    }
    console.log(reset + "reset")
  }, [selectedDoor, reset]);

这是我要更新的挂钩:

const [ reset, doReset ] = useState(0);

这是在useEffect的依赖项中进行值更改的按钮。它更改[reset]的值

<button
   onClick={() => {
     doReset(prev => prev + Math.random());
    }}> Reset </button>

编辑: 解决了!

我编辑了if语句以侦听新的重置值,从而触发了所需的操作。

 useEffect(() => {
    const { width, height } = selectedDoor;
    const scaler = 200 / Math.max(width, height);
    const w = width * scaler;
    const h = height * scaler;
    if (w !== doorWidth || h !== doorHeight || reset !== 0) {
      setDoorWidth(w);
      setDoorHeight(h);
      setCorners({
        0: {x: 0, y: 0},
        1: {x: w, y: 0},
        2: {x: w, y: h},
        3: {x: 0, y: h},
      });
      setTransformationMatrix(DEFAULT_MATRIX);
      setReset(0);
    }
    console.log(reset + "reset")
  }, [selectedDoor, reset]);

1 个答案:

答案 0 :(得分:-1)

尝试按照文档建议将{strong> doReset 重命名为 setReset