我在使用油门时面临问题。使用下面的代码,油门可以正常工作。但是,当我毫无用处setPosition([e.clientX, e.clientY])
时,出了问题。油门被打破,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
的默认行为是立即运行,并在时间集结束时(如果在那个时候将事件多次调用(。为了获得您想要的行为,您需要传递到油门通话的选项。
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
有关更多信息