【问题标题】:How to clear a settimeout in react如何在反应中清除设置超时
【发布时间】:2018-09-21 20:41:21
【问题描述】:

在每个问题组件上,我都在尝试清除超时。所以在componentWillMount() 我将启动计时器,然后在componentDidUpdate() 我将清除超时。计时器似乎不起作用。计时器到期后,我会将用户推回主页。知道为什么使用 clearTimeout() 不起作用吗?

class Questions extends Component { 
    constructor(props){
        super(props);
        this.state ={
            error: false,
            position: null,
            redirect: false
        } 
        this.error = this.error.bind(this);   
        this.errorFalse = this.errorFalse.bind(this); 
        this.timer = this.timer.bind(this); 
    }
    timer=()=>{
        setTimeout(() => { 
            console.log('this ran') 
            this.setState({
                redirect: true
            })

    }, 5000)
    }
    componentWillMount(){
        this.setState({
            error: false
        })
        this.timer();

    }
    componentDidUpdate(prevProps, prevState, snapshot, timer){
        console.log('updated')
        clearTimeout(this.timer);
    }

【问题讨论】:

标签: javascript reactjs settimeout cleartimeout


【解决方案1】:

当您使用setTimeout() 时,它会返回一个timeoutID,您可以使用它来clear 超时。

要在您的组件中使用它,您需要存储从timer 方法返回的timeoutID

class Questions extends Component {
  constructor(props) {
    super(props)
    this.state = {
      error: false,
      position: null,
      redirect: false
    }
    this.error = this.error.bind(this);
    this.errorFalse = this.errorFalse.bind(this);
    // this.timer = this.timer.bind(this); // don't bind an arrow function
  }
  timer = () => setTimeout(() => { // return the timeoutID
    console.log('this ran')
    this.setState({
      redirect: true
    })

  }, 5000);
  componentWillMount() {
    this.setState({
      error: false
    })
    this.timeoutID = this.timer(); // cache the timeoutID
  }
  componentDidUpdate(prevProps, prevState, snapshot, timer) {
    console.log('updated')
    clearTimeout(this.timeoutID); // clear the timeoutID
  }

【讨论】:

    【解决方案2】:

    反应钩子

    useEffect(() => {
        const timer = () => setTimeout(() => ...some work ... , 2000);
        const timerId = timer();
        return () => {
          clearTimeout(timerId);
        };
      });
    

    【讨论】:

    • 为什么将setTimeout 包装在一个函数中并调用它?无论如何,该函数似乎返回了setTimeout 的值,那么为什么不直接调用setTimeout 并将其值存储为timerId
    猜你喜欢
    • 2019-12-03
    • 2015-07-04
    • 2023-03-03
    • 2020-05-31
    • 1970-01-01
    • 1970-01-01
    • 2020-09-02
    • 1970-01-01
    • 2020-04-10
    相关资源
    最近更新 更多