本文介绍了componentDidMount() 中的 setTimeout() 不起作用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图在 componentDidMount() 钩子内每 5 秒更改一次组件的状态

I am trying to change the state of a component every 5 seconds as below inside componentDidMount() hook

import React, { Component } from 'react';

export default class ToTest extends Component {

  constructor(props) {
    super(props);
    this.state = {
      test: false
    };
  }

  componentDidMount() {
    setTimeout(() => { this.setState({ test: !this.state.test }) }, 5000);
  }

  renderDiv() {
    if(this.state.test) {
      return (<div>test is true</div>)
    }
    else {
      return (<div>test is false</div>)
    }
  }
  render() {
    return (
      <div>{ this.renderDiv() }</div>
    );
  }
}

但它只执行一次.它从假变为真一次,然后什么都没有.我错过了什么?

But it executes only once. It changes from false to true once and then nothing.What am I missing?

推荐答案

componentDidMount() 仅在组件挂载时执行一次,并且您只安排一次.您必须使用 setInterval() 来定期安排它.

componentDidMount() is only executed once when the component mounts and you only schedule it once. You have to use setInterval() to schedule it periodically.

此外,当您根据当前状态更新状态时,您应该在 setState() 中使用回调,该回调采用先前的状态,因为 react 可能会批处理多次调用 setState().

Also when you update the state based on the current state you should use a callback in setState() that takes the previous state as react may batch multiple calls to setState().

并且不要忘记取消componentWillUnmount()中的计时器:

And don't forget to cancel the timer in componentWillUnmount():

import React, { Component } from 'react';

export default class ToTest extends Component {
    state = {
        test: false,
    };

    componentDidMount() {
        this.timer = setInterval(
            () => this.setState(prevState => ({ test: !prevState.test })),
            5000,
        );
    }

    componentWillUnmount() {
        clearInterval(this.timer);
    }

    // other methods ...
}

这篇关于componentDidMount() 中的 setTimeout() 不起作用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

05-22 16:11