【问题标题】:How to access updated state value in same function that used to set state value [duplicate]如何在用于设置状态值的同一函数中访问更新的状态值 [重复]
【发布时间】:2018-06-27 09:43:08
【问题描述】:
class Signup extends React.Component {
  constructor() {
    super();
    this.state = { count: 0 }
  }

  hndlChange() {
    //here it's okay, It increasing count value
    this.setState({ count: this.state.count + 1 });

    //but here it printing previous value
    console.log(this.state.count);

  }
}

我正在调用这个函数。因为它增加了count 值,但是当我访问它时它返回以前的值。我想在同一个函数中访问最新更新的值我应该怎么做。

如何在同一函数中获取最新状态值

【问题讨论】:

标签: reactjs react-native react-redux


【解决方案1】:
 hndlChange();
{
  //here it's okay, It increasing count value
  this.setState({ count: this.state.count + 1 }, () => {});
}

设置状态是异步的。

【讨论】:

    【解决方案2】:

    正如here 所说,React 有额外的callback 参数。

    另外,当你想使用当前值改变你的状态时,你应该使用函数版本:

    this.setState(currentState => ({ count: currentState.count + 1 }), () => {
        console.log(this.state.count);
    });
    

    【讨论】:

    • this.setState(currentState => ({ count: currentState.count + 1 }), { console.log(this.state.count); });是的,这是更新先前状态的推荐方法,但我想获得最新值。在您的情况下,它显示 Unexpected token, expected , ERROR
    • this.setState(currentState => ({ count: currentState.count + 1 }),function() { console.log(this.state.count); });现在它的工作正常。谢谢@pwolaq
    • @KailashChoudhary 我在函数体之前忘记了() =>
    • useState() 挂钩更新器怎么样?
    猜你喜欢
    • 2022-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-05-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-01-23
    相关资源
    最近更新 更多