最好先看看我的代码:
import React, { Component } from 'react';
import _ from 'lodash';
import Services from 'Services'; // Webservice calls
export default class componentName extends Component {
constructor(props) {
super(props);
this.state = {
value: this.props.value || null
}
}
onChange(value) {
this.setState({ value });
// This doesn't call Services.setValue at all
_.debounce(() => Services.setValue(value), 1000);
}
render() {
return (
<div>
<input
onChange={(event, value) => this.onChange(value)}
value={this.state.value}
/>
</div>
)
}
}
只需简单的输入。在构造函数中,它从 props(如果可用)中获取
value
,设置组件的本地状态。
然后在
onChange
的 input
函数中,我更新状态,然后尝试调用 Web 服务端点以使用 Services.setValue()
设置新值。
有效的是,如果我直接通过输入的
debounce
设置 onChange
,如下所示:
<input
value={this.state.value}
onChange={_.debounce((event, value) => this.onChange(value), 1000)}
/>
但是随后
this.setState
仅每 1000 毫秒调用一次并更新视图。因此,在文本字段中输入内容最终看起来很奇怪,因为您输入的内容仅在一秒钟后显示。
遇到这样的情况我该怎么办?
出现这个问题是因为你没有调用debounce函数,你可以按照以下方式进行
export default class componentName extends Component {
constructor(props) {
super(props);
this.state = {
value: this.props.value || null
}
this.servicesValue = _.debounce(this.servicesValue, 1000);
}
onChange(value) {
this.setState({ value });
this.servicesValue(value);
}
servicesValue = (value) => {
Services.setValue(value)
}
render() {
return (
<div>
<input
onChange={(event, value) => this.onChange(value)}
value={this.state.value}
/>
</div>
)
}
}
针对那些来到这里的人的解决方案,因为油门/去抖不适用于
FunctionComponent
- 您需要通过 useRef(): 存储去抖函数
export const ComponentName = (value = null) => {
const [inputValue, setInputValue] = useState(value);
const setServicesValue = value => Services.setValue(value);
const setServicesValueDebounced = useRef(_.debounce(setServicesValue, 1000));
const handleChange = ({ currentTarget: { value } }) => {
setInputValue(value);
setServicesValueDebounced.current(value);
};
return <input onChange={handleChange} value={inputValue} />;
};
这篇中等文章完美地解释了发生的事情:
函数内的局部变量在每次调用后都会过期。每次 组件被重新评估,局部变量被初始化 再次。使用后面的
进行油门和去抖动工作 场景。每次计算函数组件时,您都会 注册一个新的window.setTimeout()
回调。 因此,我们将使用setTimeout
钩子,因为useRef()
返回的值不会在每次执行功能组件时重新计算。唯一的不便之处在于您必须通过useRef()
属性访问您存储的值。.current
我用微小的 lodash.throttle
和
lodash.debounce
包创建了 sandbox,这样你就可以尝试两者并选择合适的行为
对于React功能组件,debounce默认是不起作用的。您必须执行以下操作才能使其正常工作:
const debouncedFunction= React.useCallback(debounce(functionToCall, 400), []);
useCallback 使用 debounce 返回的函数并按预期工作。 不过,当您想在去抖函数内使用状态变量时,这会有点复杂(通常是这种情况)。
React.useCallback(debounce(fn, timeInMs), [])
React.useCallback 的第二个参数用于依赖项。如果您想在去抖函数中使用 state 或 prop 变量,默认情况下,它会使用旧版本的 state 变量,这将导致您的函数使用该变量的历史值,而这不是您所需要的。 要解决这个问题,您必须像在 React.useEffect 中那样包含状态变量,如下所示:
React.useCallback(debounce(fn, timeInMs), [stateVariable1, stateVariable2])
这个实现可能会解决您的目的。但您会注意到,每次随着依赖项发生变化而传递的状态变量(stateVariable1、stateVariable2)都会调用去抖函数。这可能不是您所需要的,尤其是在使用输入字段等受控组件时。
我实现的最佳解决方案是花一些时间将功能组件更改为基于类的组件并使用以下实现:
constructor(props)
{
super();
this.state = {...};
this.functionToCall= debounce(this.functionToCall.bind(this), 400, {'leading': true});
}
我为那些使用 React 函数组件的人写了一个钩子。
它是打字稿,但您可以忽略在 JavaScript 应用程序上使用的类型注释。
import { debounce, DebounceSettings } from 'lodash'
import { useRef } from 'react'
interface DebouncedArgs<T> {
delay?: number
callback?: (value: T) => void
debounceSettings?: DebounceSettings
}
export const useDebounce = <T = unknown>({ callback, debounceSettings, delay = 700 }: DebouncedArgs<T>) => {
const dispatchValue = (value: T) => callback?.(value)
const setValueDebounced = useRef(debounce(dispatchValue, delay, { ...debounceSettings, maxWait: debounceSettings?.maxWait || 1400 }))
return (value: T) => setValueDebounced.current(value)
}
export const MyInput: FC = () => {
const [value, setValue] = useState<string>('')
const debounce = useDebounce({ callback: onChange })
const handleOnInput = (evt: FormEvent<HTMLInputElement>) => {
const { value } = evt.currentTarget
setValue(value)
debounce(value)
}
function onChange(value: string) {
// send request to the server for example
console.log(value)
}
return <input value={value} onInput={handleOnInput} />
}
export const ComponentName = (value = null) => {
const [inputValue, setInputValue] = useState(value);
const setServicesValue = value => Services.setValue(value);
const setServicesValueDebounced = useCallback(_.debounce(setServicesValue, 500), []);
const handleChange = ({ currentTarget: { value } }) => {
setInputValue(value);
setServicesValueDebounced(value);
};
return <input onChange={handleChange} value={inputValue} />;
};
针对基于类的组件的 Lodash 去抖动解决方案
import { Component } from 'react'
import debounce from 'lodash/debounce'
class MyComponent extends Component {
mySearchFunction = (keyword) => {
/* API Call or something else
searchApi(keyword)
*/
}
searchWithDebounce = debounce(this.mySearchFunction, 1000)
render () {
return (<div>
<input onChange={ e => this.searchWithDebounce(e.target.value) } />
</div>)
}
export default MyComponent