状态更新后,我正在尝试访问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;
});
};
答案 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);
}
);