使用钩子 setState 时油门不工作
Throttle is not working when using hooks setState
我在使用油门时遇到问题。使用下面的代码,油门正常工作。但是,当我取消注释 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
了解更多信息
我在使用油门时遇到问题。使用下面的代码,油门正常工作。但是,当我取消注释 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
了解更多信息