有的时候我们需要拿到一个函数的返回值,将这个返回值放在this.state中,但是由于setState是异步执行的,所以可能不能立即拿到改变的结果。本人这里遇到两种可解决问题的方案
第一种,在生命周期函数中拿到函数的返回值,将其放入this.state中
未修改的代码
async componentDidMount() {
var newCode = await this.randomCode();
this.setState({
code: newCode
});
}
上面的代码没办法拿到最新
async componentDidMount() {
var newCode = await this.randomCode();
this.setState({
code: newCode
})
}
async 是es7的语法糖,想具体了解的看这里:http://es6.ruanyifeng.com/#docs/async
第二种,在非生命周期函数中,拿到函数的返回值,将其放入this.state中
change = () => {
let change_code = this.randomCode();
// 下面两步很重要
let state = this.state;
state.code = change_code;
this.setState(state);
}