setState()之后的setState回调函数上的this.state

时间:2019-04-18 06:19:13

标签: reactjs

状态更新后,我正在尝试访问this.setState中的this.state。 我希望将用户信息设置为状态,然后从该事实来源将用户数据保存到本地存储中

setUserInfo = userInfo => {
  this.setState(
    { username: userInfo.userName, password: userInfo.userPass },
    prevState => {
      //trying to access this.state but unable to
      console.log(prevState);
      // or
      console.log(this.state.username);
    }
  );
};

我知道这可以编写代码,但是会确认第二个setstate在第一个setState之后运行吗?

setUserInfo = userInfo => {
  this.setState({ username: userInfo.userName, password: userInfo.userPass });
  this.setState(prevState => {
    prevState;
  });
};

2 个答案:

答案 0 :(得分:1)

您绑定了功能

在您的builder()内部绑定函数

this.handleClick = this.handleClick.bind(this)

handleClick() {
    this.setState({ status: 2 }, () => {
      console.log(this.state);
    });
  }

实际上这应该可行

答案 1 :(得分:0)

this函数内的

setState()指的是setState的方法,因此要区分这两个this。设置var that = this,以便像that.state.username

一样使用它
var that = this;

this.setState(
  { username: userInfo.userName, password: userInfo.userPass },
  prevState => {
    //tring to access this.state.username but unable to
    console.log(prevState.username, that.state.username);
  }
);