代码之家  ›  专栏  ›  技术社区  ›  AlienMind

设置React中的状态未提供所需输出

  •  0
  • AlienMind  · 技术社区  · 8 年前

    下面是我的代码。它给我的结果是0,1,2,4,8,16。。。。这有什么问题吗。我是新来的。 从“react”导入{react,Component}

    class Timer extends Component{
    
       constructor(props){
    
          super(props);
          this.state={
          count:0
          }
    }
    
    updateTime(){
        setInterval(() => {
                          var number=this.state.count+1;
                         this.setState({ count:number })} , 5000);
                }
    
    render(){
       this.updateTime()
           return(
            <div>
                <h1>{this.state.count}</h1>
            </div>
            )
        }
    
    }
    export default Timer;
    

    然而,如下所示更改updateTime函数会得到预期的结果

    updateTime(){
       var number=this.state.count;
       setInterval(() => {
       number++;
       this.setState({ count:number })}, 5000);
     }
    

    预期结果:-每5秒增加1个数字

    2 回复  |  直到 8 年前
        1
  •  1
  •   Andy Ray    8 年前

    每次渲染时,都会调用 updateTime() ,启动一个新计时器。

    仅呼叫 updateTime() 在里面 componentDidMount 而不是在 render .

    请确保在卸载时清除计时器:

    componentDidMount() {
        this.timer = this.updateTime();
    }
    
    componentWillUnmount() {
        clearInterval(this.timer);
    }
    
    updateTime(){
        return setInterval(() => {
            var number=this.state.count+1;
            this.setState({ count:number })
        }, 5000);
    }
    
        2
  •  0
  •   Ben Kolya Mansley    8 年前

    每次状态更新时 render() 函数运行。你在打电话 this.updateTime() 每一次 render() 运行,即多次设置间隔。在4次渲染调用之后,您将运行4个计时器,每个计时器都会增加 state.count 每次按1。要减少间隔数,只需设置一次间隔:

    componentDidMount() {
        this.updateTime();
    }