反应增量递减计数问题

时间:2017-08-06 07:24:09

标签: reactjs

  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两次,则控制台会显示0和{{1} },然后我点击1控制台显示decrement2,这导致我的程序运行不正确。我期待的是11,然后21

如何使0正确的递增/递减计数?

更新:

在搜索了一段时间后我改为下面,现在它正常工作,real-time使componentWillUpdate()有点慢

update

3 个答案:

答案 0 :(得分:2)

this.setState()异步更新this.state的值。由于您在调用console.log(this.state)后立即同步进行this.setState()调用,此时this.state的值尚未更改 - 您只是记录当前值。

要访问并记录更新的this.state,在执行异步更新后,您可以使用lifecycle hook componentDidUpdate()

答案 1 :(得分:1)

this.setState()是异步方法,它表示当前状态。

所以你有两种方法可以获得下一个状态。

1。react-state-promise

2.使用反应组件生命周期方法。

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

答案 2 :(得分:0)

这是因为this.setState异步工作。 如果你想拥有正确的console.logs,你应该使用这样的代码:

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

https://facebook.github.io/react/docs/state-and-lifecycle.html#state-updates-may-be-asynchronous

相关问题