我在使用 throttle 时遇到问题。使用下面的代码, throttle 正常工作。但是,当我取消注释 setPosition([e.clientX, e.clientY])
时出现问题。 throttle 坏了,position
立即更新,无需等待 1 秒。
import React, { useState } from 'react'
import { throttle } from 'lodash'
export default () => {
const [position, setPosition] = useState([0, 0])
const [x, y] = position
const handleMouseMoveThrottle = throttle(e => {
console.log(e.clientX, e.clientY)
// setPosition([e.clientX, e.clientY])
}, 1000)
const handleMouseMove = e => {
e.persist()
handleMouseMoveThrottle(e)
}
return (
<div
style={{ width: 300, height: 300, border: 'solid 1px black' }}
onMouseMove={handleMouseMove}
>
<div>
Position: {x}, {y}
</div>
</div>
)
}
有什么解决办法吗?
最佳答案
lodash throttle
的默认行为是在设置的时间结束时立即运行(如果该事件在该时间内被调用多次)。为了获得您想要的行为,您需要将选项传递给 throttle 调用。
const handleMouseMoveThrottle = throttle(e => {
console.log(e.clientX, e.clientY)
// setPosition([e.clientX, e.clientY])
}, 1000, { leading: false }); // this says, do not run the function immediately
默认情况下 leading
设置为 true
,另一个选项 trailing
也设置为 true
.
看看这个:
https://lodash.com/docs/4.17.11#throttle
还有这个:
https://github.com/lodash/lodash/blob/master/throttle.js#L52
获取更多信息
关于reactjs - 使用钩子(Hook) setState 时 throttle 不工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56159399/