2017-08-06 100 views
1
increment: function() { 
    this.setState({ 
     counter: this.state.counter + 1 
    }); 
    console.log(this.state.counter) 
    }, 

    decrement: function(){ 
    this.setState({ 
     counter: this.state.counter - 1 
    }); 
    console.log(this.state.counter) 
    }, 

    calFun: functin(){ 
    this.state.counter * 5; // incorrect 
    } 

    render: function() { 
    return <div> 
     <div id='counter'>{this.state.counter}</div> 
     <button onClick = {this.increment}> +1 </button> 
     <button onClick = {this.decrement}> -1 </button> 
    </div> 
    } 

{this.state.counter}輸出數字顯示正常,但是,console.log總是計數one more例如,如果我點擊increment兩次,控制檯顯示01,然後我點擊decrement控制檯顯示21這引起我的程序運行不正確。我所期待的12,然後10反應增量遞減計數問題

如何有real-time正確的遞增/遞減計數?

UPDATE:

搜索了一會兒我改變了下面,現在它工作得很好,快速後,componentWillUpdate()使得update有點慢

this.setState({ 
     counter: ++this.state.counter 
    }); 

this.setState({ 
     counter: --this.state.counter 
    }); 

回答

2

this.setState()異步更新的this.state值。由於您在撥打this.setState()後立即同步撥打您的console.log(this.state)電話,此時this.state的值尚未更改 - 您只需記錄當前值。

訪問和登錄更新this.state,異步更新已被執行之後,您可以使用lifecycle hookcomponentDidUpdate()

1

this.setState()是異步的方法,這意味着當前的狀態。

所以你有兩種方法來獲得下一個狀態。

1. react-state-promise

2.使用反應組分生命週期方法。

shouldComponentUpdate(nextProps,nextState)/ componentWillUpdate(nextProps,nextState)