【问题标题】:Debounce doesn't respect the timeoutDebounce 不考虑超时
【发布时间】:2018-08-19 01:15:49
【问题描述】:

我正在尝试设置一个去抖函数来处理 HTTP 请求函数。代码和下面的很相似,基本上我只是改了函数命名而已。

首先,我正在使用这个去抖动功能。

function debounced(fn, delay) {
let timerId;
return function (...args) {
    if (timerId) {
        clearTimeout(timerId);
    }
    timerId = setTimeout(() => {
        fn(...args);
        timerId = null;
    }, delay);
}}

还有一个基本 React'js 类的示例代码。

var Example = React.createClass({
getInitialState: function () {
    return ({
        counter: 0
    });
},
clickEvt: function () {
    console.log("hey!!");
    this.setState({counter: this.state.counter + 1});
    return debounced(request(this.props.counter), 3000);
},

render: function () {
    return (
        <button onClick={this.clickEvt}>hit me</button>;
    );
}});

问题是,debounced 函数在我每次点击该按钮时都会运行请求。有什么问题?

【问题讨论】:

    标签: javascript reactjs debouncing


    【解决方案1】:

    您每次单击时都会重新创建一个去抖动的函数,因此这将不起作用。您需要创建一次并使用它。

    您还直接调用您的函数。 这应该有效:

    var Example = React.createClass({
    getInitialState: function () {
        return ({
            counter: 0
        });
    },
    debouncedRequest: debounce(function() {
       request(this.props.counter);
    }, 3000),
    clickEvt: function () {
        console.log("hey!!");
        this.setState({counter: this.state.counter + 1});
        return this.debouncedRequest();
    },
    
    render: function () {
        return (
            <button onClick={this.clickEvt}>hit me</button>;
        );
    }});
    

    【讨论】:

    • 该函数仅在 3000 毫秒后被调用,因此我们可以说它具有正常的行为,尽管由于我无法访问 this.props 甚至 this 的值而出现范围错误.state 在 debounceRequest 中。你知道怎么解决吗?
    • 当你调用你的函数时,你失去了这个。您需要找到一种方法将其绑定到您的去抖函数。我不知道 createClass 的正确方法是什么。当你在使用 ES6 时,为什么你需要用现代的方式来响应类?
    • 其实,谢谢。主要问题是我使用的功能没有正确实现。
    猜你喜欢
    • 2015-04-24
    • 2021-03-11
    • 2017-10-24
    • 2015-01-14
    • 1970-01-01
    • 1970-01-01
    • 2013-09-22
    • 1970-01-01
    • 2016-01-12
    相关资源
    最近更新 更多