reactjs - 使用钩子(Hook) setState 时 throttle 不工作

标签 reactjs react-hooks throttling

我在使用 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/

相关文章:

javascript - 右键菜单触发其父菜单项的单击事件

javascript - 下载属性在 React js 中的 <a></a> 链接内不起作用

javascript - 状态设置方法没有影响主对象 - ReactJS

javascript - 无法在 React Native 中使用新的 Textinput 数据更新 Array 对象

javascript - 如何限制返回输出的 typescript 函数

python - 限制Python中的函数调用

reactjs - 找不到模块 : Can't resolve '@aws-amplify/core'

javascript - 如何使 React-Day-Picker 月份水平并排而不是垂直对齐

javascript - 如何从 renderer.js 调用 react 组件代码?

Twilio 队列溢出错误 : how large is the queue?