在reactjs中停止超时?

Blu*_*xir 16 settimeout reactjs

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

setTimeout(function() {
//do something
}.bind(this), 3000);
Run Code Online (Sandbox Code Playgroud)

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

Jon*_*nan 21

假设这发生在组件内部,请存储超时ID,以便稍后取消.否则,您需要将id存储在稍后可以从其访问的其他位置,就像外部存储对象一样.

this.timeout = setTimeout(function() {
  // Do something
  this.timeout = null
}.bind(this), 3000)

// ...elsewhere...

if (this.timeout) {
  clearTimeout(this.timeout)
  this.timeout = null
}
Run Code Online (Sandbox Code Playgroud)

您可能还想确保任何挂起的超时也被取消componentWillUnmount():

componentWillUnmount: function() {
  if (this.timeout) {
    clearTimeout(this.timeout)
  }
}
Run Code Online (Sandbox Code Playgroud)

如果你有一些UI取决于超时是否挂起,你需要将id存储在适当的组件状态中.


jmg*_*gem 11

由于现在不推荐使用React mixins,这里是一个更高阶组件的示例,它包装了另一个组件,以提供与接受的答案中描述的功能相同的功能.它整齐地清理卸载时剩余的任何超时,并为子组件提供API以通过props管理它.

这使用了ES6类和组件组合,这是2017年替换mixins的推荐方法.

在Timeout.jsx中

import React, { Component } from 'react';

const Timeout = Composition => class _Timeout extends Component {
    constructor(props) {
      super(props);
    }

    componentWillMount () {
      this.timeouts = [];
    }

    setTimeout () {
      this.timeouts.push(setTimeout.apply(null, arguments));
    }

    clearTimeouts () {
      this.timeouts.forEach(clearTimeout);
    }

    componentWillUnmount () {
      this.clearTimeouts();
    }

    render () {
      const { timeouts, setTimeout, clearTimeouts } = this;

      return <Composition 
        timeouts={timeouts} 
        setTimeout={setTimeout} 
        clearTimeouts={clearTimeouts} 
        { ...this.props } />
    }
}

export default Timeout;
Run Code Online (Sandbox Code Playgroud)

在MyComponent.jsx中

import React, { Component } from 'react';
import Timeout from './Timeout';    

class MyComponent extends Component {
  constructor(props) {
    super(props)
  }

  componentDidMount () {
    // You can access methods of Timeout as they
    // were passed down as props.
    this.props.setTimeout(() => {
      console.log("Hey! I'm timing out!")
    }, 1000)
  }

  render () {
    return <span>Hello, world!</span>
  }
}

// Pass your component to Timeout to create the magic.
export default Timeout(MyComponent);
Run Code Online (Sandbox Code Playgroud)

  • 为什么你必须经历这一切?乔尼·布坎南的答案有什么问题? (2认同)

Tom*_*uba 10

你应该使用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;
Run Code Online (Sandbox Code Playgroud)

......并在你的组件中:

// 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;
Run Code Online (Sandbox Code Playgroud)

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

  • 如何使用ES6类转换为React?Mixins即将被弃用. (13认同)