react 拿到函数的值,设置到this.setState()中

有的时候我们需要拿到一个函数的返回值,将这个返回值放在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);
    }

 

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值