Typescript 警告、详尽的依赖项、useEffect 依赖项列表

问题描述 投票:0回答:1

我最近也遇到这个问题,但一直没去深究。列出 useEffect 依赖项时,Typescript 会发出警告,非常贴心,它理解我应该将什么作为依赖项:

React Hook useEffect has a missing dependency: 'radius'. Either include it or remove the dependency array.eslintreact-hooks/exhaustive-deps
。 但是为什么在包含这两个依赖项时它会抛出此错误:
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' }} />
    );
}

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

reactjs typescript canvas react-hooks
1个回答
0
投票

该函数不是原语,它是一个对象。因此,每次组件 Ball 重新渲染时,都会重新创建函数drawBall。旧的 drawBall 和新的 drawBall 不相等。它会触发 useEffect

一些解决方案:

  1. 将其从 useEffect 中删除

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

  3. 使用 useCallback 钩子

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

    useEffect(() => { //逻辑 }, [drawBall, 半径]);

© www.soinside.com 2019 - 2024. All rights reserved.