javascript Lodash 去抖动在 React 中不起作用
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/47809666/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Lodash debounce not working in React
提问by Shubham Khatri
it would be best to first look at my code:
最好先看看我的代码:
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>
)
}
}
Just a simple input. In the contructor it grabs valuefrom the props (if available) at sets a local state for the component.
只是一个简单的输入。在构造函数中,它value从道具(如果可用)中抓取并为组件设置本地状态。
Then in the onChangefunction of the inputI update the state and then try to call the webservice endpoint to set the new value with Services.setValue().
然后在I的onChange函数中input更新状态,然后尝试调用 webservice 端点以设置新值Services.setValue()。
What does work is if I set the debouncedirectly by the onChangeof the input like so:
什么工作是如果我debounce直接通过onChange输入设置 像这样:
<input
value={this.state.value}
onChange={_.debounce((event, value) => this.onChange(value), 1000)}
/>
But then this.setStategets called only every 1000 milliseconds and update the view. So typing in a textfield ends up looking weird since what you typed only shows a second later.
但随后this.setState仅每 1000 毫秒调用一次并更新视图。因此,在文本字段中输入最终看起来很奇怪,因为您输入的内容仅在一秒钟后显示。
What do I do in a situation like this?
遇到这种情况我该怎么办?
回答by Shubham Khatri
The problem occurs because you aren't calling the debounce function, you could do in the following manner
出现问题是因为你没有调用 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>
)
}
}

