【问题标题】:Using debounce with react don't fire function使用 debounce 和 react 不触发功能
【发布时间】:2018-02-16 00:29:02
【问题描述】:
我想在 react 中去抖一个函数,
import { debounce } from 'lodash';
<button onClick={this.handleClickDebounce}>Debounce click</button>
handleClickDebounce = () => {
debounce(this.fire_something, 500);
};
这里有什么问题?该功能甚至没有被触发。我在下面创建了一个演示
https://codesandbox.io/s/1r4k3r2z8l
【问题讨论】:
标签:
javascript
reactjs
ecmascript-6
lodash
【解决方案2】:
在constructor 中进行操作。在您的示例中,每次单击按钮时都会创建去抖动功能。但是函数应该只去抖动一次。
工作示例 - https://codesandbox.io/s/rr6w91p3wo(打开控制台并尝试单击按钮)。
class App extends Component {
constructor() {
super();
this.handleClickDebounce = debounce(this.handleClick, 500);
}
handleClick = () => {
this.fire_something();
};
fire_something = () => {
console.log("fire");
};
render() {
return (
<div>
<button onClick={this.handleClick}>Normal click</button>
<br />
<button onClick={this.handleClickDebounce}>Debounce click</button>
</div>
);
}
}
ReactDOM.render(<App />, document.getElementById("root"));