使用钩子setState时,油门不起作用

时间:2019-05-16 00:50:38

标签: reactjs react-hooks throttling

使用节气门时遇到问题。使用下面的代码,油门可以正常工作。但是,当我取消注释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>
  )
}

有解决方案吗?

1 个答案:

答案 0 :(得分:1)

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

了解更多信息