useEffect 如何监控 useRef.current 里面的值发生变化(useRef不绑定dom)?
function handleWheel(e: TKWheelEvent) {
if (e.evt.ctrlKey) return
e.evt.preventDefault()
const direction = e.evt.deltaY > 0 ? -1 : 1
const stage = e.target.getStage()!
const oldScale = stage.scaleX()
const pointer = stage.getPointerPosition()!
const mousePointTo = {
x: pointer.x / oldScale - stage.x() / oldScale,
y: pointer.y / oldScale - stage.y() / oldScale,
}
const { MaxScale, MinScale } = ScaleRef.current
const newScale =
direction > 0
? oldScale > MaxScale
? oldScale
: oldScale * ScaleBy
: oldScale < MinScale
? oldScale
: oldScale / ScaleBy
stage.scale({ x: newScale, y: newScale })
ScaleRef.current = { // 这里发生了改变!
...ScaleRef.current,
newScale,
}
}
useEffect(() => {
console.log(ScaleRef.current.newScale)
}, [ScaleRef.current]) // 这样不打印
}, [ScaleRef]) // 这样不打印
}, [ScaleRef.current.newScale]) // 这样不打印
<ScStage ref={stageRef} onWheel={handleWheel} />
其实我是想让 ScaleRef.current.newScale
发生变化的时候传给子组件,让子组件重新渲染,但是发现ScaleRef.current.newScale
这玩意监听不到它的变化
两个误区吧:
解决思路:在更新 ScaleRef.current 的地方,直接写 useEffect 里的逻辑即可(有全量代码的话,视情况而定)。