React 自动递增计数器

问题描述 投票:0回答:2

我完全从我正在关注的 Youtube React 教程中复制了这段代码。但他们得到的结果和我得到的结果完全不同。

 class Contact extends Component {
        constructor(props) {
            super(props);
            this.state = { counter: 0 };
        }
        increment() {
            setTimeout(() => {
                this.setState((prev,props)=>({ counter: prev.counter + 1 }));
            }, 3000);
        }
        render() {
            this.increment();
            return (
                    <div>
                        <p>{this.state.counter}</p>
                    </div>
            );
        }
    }
    
    export default Contact;

预期结果:1 2 3 4 5 6 7 8 9 10 11 12 .....

获得的结果:2 4 6 8 12 18 26 34 42 50 56 66 ....

reactjs state settimeout setstate
2个回答
0
投票

您在

increment()
内调用
render()
,因此间隔函数会一遍又一遍地初始化,从而导致不可预测的行为。

您需要保证,间隔仅初始化一次。因此,您可以使用生命周期钩子

componentDidMount()
,该钩子在组件安装后执行。对于间隔和超时,您还应该确保在卸载时清除它们。
componentWillUnmount()
是完成此任务的工具。

遵循可行的解决方案:

class Contact extends Component {
  constructor(props) {
    super(props);
    this.state = {
      count: 0,
    };
    this.interval = null;
  }

  componentDidMount() {
    this.interval = setInterval(() => {
      this.setState({
        count: this.state.count + 1,
      });
    }, 3000);
  }

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

  render() {
    return <div>{this.state.count}</div>;
  }
}

0
投票

当我尝试这个自动计数器时,我将使用 setinterval 和 settimeout 方法,但在我找到这个解决方案之后。如果有人给我对此的反馈

export default function App() {
  let [counter, setCounter] = useState(0);

  function incCounter() {
    console.log("callled");
    setCounter(counter + 1);
  }
 
  setTimeout(incCounter, 1000);

  return (
    <div className="App">
    
      <h1>{counter}</h1>
      
    </div>
  );
}

© www.soinside.com 2019 - 2024. All rights reserved.