为什么 canvas 函数内的变量值不递增?

Why variable value inside of canvas function not incrementing?

这是一个未解决的 GitHub 问题 Github Issue

这是一个Expo Snack

出于某种原因,canvas 函数内部的变量没有递增,而外部工作正常。请看看我的代码:

function home ({ navigation }) {

const [counter, setCounter] = useState(330);

      useEffect(() => {
      const timeout = setTimeout(() => {
      setCounter(counter + 1);
      }, 1000);
  
      return () => {
      clearTimeout(timeout);
      };
  }, [counter]);

console.log('outside ', counter);

    const _onGLContextCreate = (gl) => {
        var ctx = new Expo2DContext(gl);

     //   setInterval(() => {
     //       console.log('set interval doesnt refresh too ', counter);
     //   }, 1000);

console.log('inside ', counter);
    
    let circle = {
        x: counter, 
        y: 100,
        radius: 30,
        color: 'black'
    }
    
    let circle2 = {
        x: 400,
        y: 100,
        radius: 30,
        color: 'blue'
    }
    
        function drawCircle() {
            ctx.beginPath();
            ctx.arc(circle.x, circle.y, circle.radius, 0, Math.PI * 2);
            ctx.fillStyle = circle.color;
            ctx.fill();
            ctx.closePath();
        }
    
        function drawCircle2() {
            ctx.beginPath();
            ctx.arc(circle2.x, circle2.y, circle2.radius, 0, Math.PI * 2);
            ctx.fillStyle = circle2.color;
            ctx.fill();
        }

        function update() {
            drawCircle();
            drawCircle2();
        }

        function animate() {
        ctx.clearRect(0, 0, ctx.width, ctx.height);
        requestAnimationFrame(animate);
    
        update();
    
        ctx.flush();
        }
    
        animate();
    
        ctx.stroke();
        ctx.flush();
    };

    
    return (
            <GLView style={{ flex: 1 }} onContextCreate={_onGLContextCreate} />
    );
}

export { home };

日志显示如下:

outside  330
inside  330
outside  331
outside  332
outside  333
outside  334
outside  335
outside  336
outside  337

有谁知道为什么在 canvas 中被读取一次,以及在 canvas 函数中将其递增的解决方案是什么?

我不知道到底是什么原因,但我发现了体系结构中的问题,当我修复它们时它就起作用了。 TL;DR 在此处查看结果 https://snack.expo.dev/@dozsolti/expogl-ball

  1. 您不需要重新渲染组件,因为您只更新了 canvas,所以 useState 将与 useRef 交换。此外,您可能打算每秒更新一次计数器,因此我将 useTimeout 更改为 useInterval。 (useTimeout 工作只是因为它在一个 useEffect 中更新了计数器依赖,有点像调用他自己。正确的方法是在加载组件时使用 useEffect 和 setInterval)
  2. 之后您需要将 countercounter.current
  3. 交换
  4. 请记住,_onGLContextCreate 仅 运行 一次,因此 circle 和 circle2 对象不会更改。那就是我们在更新
  5. 中更改了我更改的x值

除此之外,一切看起来都很好,我想你稍微优化了代码,比如创建一个以 x、y 作为参数的单个 DrawCircle 函数,等等。