react中直接使用lodash的debounce函数,发现并未生效,1秒内多次触发,控制台仍有多次打印,这是因为debounceSearch函数被重新定义了,需要使用useCallback来包装函数。

import { ChangeEvent } from "react"
import { useCallback, useState } from "react"
import { Input } from "antd"
import _ from "lodash"

export default () => {
	const [idValue, setIdValue] = useState<string>("")
	const debounceSearch = _.debounce((value) => {
	    console.log(value)
	  }, 1000)
	)
	const onIptChange = (e: ChangeEvent<HTMLInputElement>) => {
	  debounceSearch(e.target.value)
	}

	return <Input value={idValue} onChange={onIptChange}/>
}

使用useCallback,可以将这个函数缓存起来,避免重复定义。

const debounceSearch = useCallback(
  _.debounce((value) => {
    console.log(value)
  }, 1000),
  []
)
02-22 20:50