【问题标题】:How to use useCallback to operate always on the fresh arguments?如何使用 useCallback 始终对新参数进行操作?
【发布时间】:2022-06-29 22:54:37
【问题描述】:

这里有什么问题?

    const [numOfRenderInProgress, setNumOfRenderInProgress] = useState<number>(-1)
    
    const decrease = useCallback(() => {
        setNumOfRenderInProgress(numOfRenderInProgress - 1)
    }, [numOfRenderInProgress])

    const draw = (ctx) => {
        let i = 0

        if (imgId1) {
            let i1 = new Image()
            i1.src = `https://${bucket}.s3.eu-central-1.amazonaws.com/${imgId1}`
            i1.crossOrigin = 'anonymous'
            i++
            i1.onload = () => {
                ctx.drawImage(i1, 114, -6, 252, 464)
                decrease()
            }
        }

调用decrease 不会考虑“最近”状态,而是考虑调用时间。

【问题讨论】:

  • 我不太明白这个问题,但你知道setNumOfRenderInProgress 接收当前状态作为参数吗?

标签: reactjs


【解决方案1】:

可能是这样的:

i1.onload = () => {
                ctx.drawImage(i1, 114, -6, 252, 464)
                decrease()
            }

如果此onload 回调仅在初始渲染期间创建,并在后续渲染中调用,则它将引用旧的decrease 函数。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-05-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-02-10
    相关资源
    最近更新 更多