Reactjs 与React一起使用时未调用requestAnimationFrame回调

Reactjs 与React一起使用时未调用requestAnimationFrame回调,reactjs,animation,requestanimationframe,Reactjs,Animation,Requestanimationframe,我试图用react组件包装画布组件,并设置requestAnimationFrame,以便能够在画布上绘制动画 我有一个简单的组件,它试图简单地画一个圆: import * as React from "react"; import { useLayoutEffect, useRef } from "react"; export interface Props {} export const Loop: React.FC<Props> =

我试图用react组件包装画布组件,并设置requestAnimationFrame,以便能够在画布上绘制动画

我有一个简单的组件,它试图简单地画一个圆:

import * as React from "react";
import { useLayoutEffect, useRef } from "react";

export interface Props {}

export const Loop: React.FC<Props> = () => {
  const cv = useRef<HTMLCanvasElement>(null);
  const oldTimestamp = useRef<number>(0);

  useLayoutEffect(() => {
    let animationID = 0;

    console.log("USEEFFECT");

    const loop = (timestamp: number) => {
      let secondsPassed = (timestamp - oldTimestamp.current) / 1000;
      secondsPassed = Math.min(secondsPassed, 0.1);

      oldTimestamp.current = timestamp;

      console.log("LOOP");

      update(secondsPassed);
      draw();

      animationID = requestAnimationFrame(loop);
    };

    animationID = requestAnimationFrame(loop);

    return cancelAnimationFrame(animationID);
  }, []);

  const update = (secondsPassed: number) => {};

  const draw = () => {
    console.log("DRAW");
    const ctx = cv && cv.current && cv.current.getContext("2d");
    if (ctx) {
      ctx.beginPath();
      ctx.arc(100, 75, 50, 0, 2 * Math.PI);
      ctx.stroke();
    }
  };

  return (
    <div>
      <canvas ref={cv}></canvas>
    </div>
  );
};
import*as React from“React”;
从“react”导入{useLayoutEffect,useRef};
导出接口道具{}
导出常量循环:React.FC=()=>{
const cv=useRef(空);
const oldTimestamp=useRef(0);
useLayoutEffect(()=>{
设animationID=0;
console.log(“useffect”);
常量循环=(时间戳:数字)=>{
设secondsPassed=(timestamp-oldtimstamp.current)/1000;
secondsPassed=数学最小值(secondsPassed,0.1);
oldTimestamp.current=时间戳;
console.log(“循环”);
更新(第二次);
draw();
animationID=请求AnimationFrame(循环);
};
animationID=请求AnimationFrame(循环);
返回cancelAnimationFrame(animationID);
}, []);
const update=(secondsPassed:number)=>{};
常量绘图=()=>{
控制台日志(“绘图”);
const ctx=cv&&cv.current&&cv.current.getContext(“2d”);
如果(ctx){
ctx.beginPath();
ctx.arc(100,75,50,0,2*Math.PI);
ctx.stroke();
}
};
返回(
);
};
我已经添加了三个
console.log
调用来帮助识别发生了什么。仅ATM
console.log(“useffect”),但没有其他记录。在我看来,
animationID=requestAnimationFrame(循环)useLayoutEffect
中的code>未调用
循环
回调

我认为
useLayoutEffect
中的
requestAnimationFrame
设置是正确的


我做错了什么?

您应立即取消动画帧,而应返回函数:


return()=>cancelAnimationFrame(animationID)

如果立即取消动画帧,则应返回函数:


return()=>cancelAnimationFrame(animationID)

谢谢!有时候你只需要另一双眼睛:)谢谢!有时候你只需要另一双眼睛:)