在 reactjs 中停止超时? [英] stopping a timeout in reactjs?

查看:97
本文介绍了在 reactjs 中停止超时?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有没有办法在 reactjs 中杀死/(摆脱)超时?

Is there a way I can kill/(get rid of) a timeout in reactjs?

setTimeout(function() {
//do something
}.bind(this), 3000);

通过某种点击或操作,我希望能够完全停止并结束超时.有没有办法做到这一点?谢谢.

Upon some sort of click or action, I want to be able to completely stop and end the timeout. Is there a way to do this? thanks.

推荐答案

你应该使用 mixins:

You should use mixins:

// file: mixins/settimeout.js:

var SetTimeoutMixin = {
    componentWillMount: function() {
        this.timeouts = [];
    },
    setTimeout: function() {
        this.timeouts.push(setTimeout.apply(null, arguments));
    },

    clearTimeouts: function() {
        this.timeouts.forEach(clearTimeout);
    },

    componentWillUnmount: function() {
        this.clearTimeouts();
    }
};

export default SetTimeoutMixin;

...并在您的组件中:

...and in your component:

// sampleComponent.js:
import SetTimeoutMixin from 'mixins/settimeout'; 

var SampleComponent = React.createClass({

    //mixins:
    mixins: [SetTimeoutMixin],

    // sample usage
    componentWillReceiveProps: function(newProps) {
        if (newProps.myValue != this.props.myValue) {
            this.clearTimeouts();
            this.setTimeout(function(){ console.log('do something'); }, 2000);
        }
    },
}

export default SampleComponent;

更多信息:https://facebook.github.io/react/docs/reusable-components.html

这篇关于在 reactjs 中停止超时?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆