reactjs - 如何在用于设置状态值的同一函数中访问更新的状态值

标签 reactjs react-native react-redux

这个问题在这里已经有了答案:





Why calling react setState method doesn't mutate the state immediately?

(7 个回答)



setState doesn't update the state immediately

(15 个回答)


3年前关闭。



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 value 但是当我访问它时它返回以前的值。我想在同一个函数中访问最新的更新值,我应该怎么做。

如何在同一函数中访问最新状态值

最佳答案

如前所述 here React 有额外的 callback范围。

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

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

关于reactjs - 如何在用于设置状态值的同一函数中访问更新的状态值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48319251/

相关文章:

javascript - 为什么 scrollView 在我的代码中不能以垂直方式工作?

javascript - 在 React Native 中使用地理围栏

reactjs - 如何在 Firebase firestore 中使用用户 'uid' 创建文档

react-native - React Native 应用程序 Netinfo 返回未知

android - React-native:在 Android 中允许音频的权限

reactjs - 未找到模块 : Can't resolve 'react'

javascript - 在 React 组件之外访问 Redux Store 会返回初始值

reactjs - React MUI V5 AppBar 背景颜色不改变

javascript - React 无法读取未定义的属性 'bind'

reactjs - 如何确保 Redux Saga 中数据不会加载两次?