我最近遇到了这个问题,但从来没有关心过这个问题.在列出useEffect个依赖项时,一个Typescift给出了一个警告,非常甜蜜,它理解了我应该把什么作为依赖项:React Hook useEffect has a missing dependency: 'radius'. Either include it or remove the dependency array.eslintreact-hooks/exhaustive-deps. 但是为什么它会抛出这个错误时,包括这两个dep: The 'drawBall' function makes the dependencies of useEffect Hook (at line 41) change on every render. Move it inside the useEffect callback. Alternatively, wrap the definition of 'drawBall' in its own useCallback() Hook.eslintreact-hooks/exhaustive-deps,认为既然它是在deps列表中,将它放在useEffect()本身中是很自然的,但仍然不能完全理解它的逻辑.

export default function Ball({ radius }: BallProps) {
    const ball = new Image()
    ball.src = "/billiard.png"

    const canvasRef = useRef<HTMLCanvasElement>(null);

    const drawBall: DrawBallProps = (ctx, radius) => {

        // Ball
        ctx.drawImage(ball, 0, 0, radius * 2, radius * 2);
               
        //animate the ball
    };
    
    useEffect(() => {
        const canvas = canvasRef.current;
        if (!canvas) return;
        
        const ctx = canvas.getContext('2d');
        if (!ctx) return;

        
        const render = () => {
            ctx.clearRect(0, 0, canvas.width, canvas.height);
            drawBall(ctx, radius);
            requestAnimationFrame(render);
            console.log('rendered');
        };

        render();
    }, [drawBall, radius]);

    return (
        <canvas ref={canvasRef} width={100} height={100} style={{ border: '1px solid black' }} />
    );
}

如果我不包括绘图函数或半径作为依赖项,会有什么变化吗?,是的…我在这方面很糟糕…

推荐答案

函数不是一个原语,而是一个对象.因此,每次组件Ball重新呈现函数drawBall重新创建.旧drawBall和新drawBall是不一样的.触发useEffect.

一些解决方案:

  1. 删除它的deps of use效果

  2. 将其移至useEffect(在您的情况下,首选解决方案)

  3. 使用使用回调挂钩

    const drawBall:DrawBallProps = useCallback((ctx,radius)={> //逻辑 };

    UseEffect(()=>;{ //逻辑 },[DrawBall,Radius]);

Typescript相关问答推荐

有没有可能使用redux工具包的中间件同时监听状态的变化和操作

泛型和数组:为什么我最终使用了`泛型T []`而不是`泛型T []`?<><>

对深度对象键/路径进行适当的智能感知和类型判断,作为函数参数,而不会触发递归类型限制器

如何在TypeScrip面向对象程序设计中用方法/属性有条件地扩展类

我想创建一个只需要一个未定义属性的打字脚本类型

带switch 的函数的返回类型的类型缩小

嵌套对象的类型

类型TTextKey不能用于索引类型 ;TOption

如何将定义模型(在Vue 3.4中)用于输入以外的其他用途

为什么&;(交集)运算符会删除不相交的属性?

如何缩小函数的返回类型?

打字错误推断

如何在Reaction Native中关注屏幕时正确更新状态变量?

使用&reaction测试库&如何使用提供程序包装我的所有测试组件

基于闭包类型缩小泛型类型脚本函数的范围

基于属性值的条件类型

Typescript泛型验证指定了keyof的所有键

传入类型参数<;T>;变容函数

广义泛型类型不加载抽象类型上下文

对象可能未定义(通用)