javascript - react willmount调用 promise .then拿到数据了 设置state失败?

查看:79
本文介绍了javascript - react willmount调用 promise .then拿到数据了 设置state失败?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

问 题

拿到数据 设置state失败 烦请直接看代码

这里是state

state = {
    data: {}
  
  }

componentWillMount

   componentWillMount () {
    this.getTask('10-24', 'A')
  }


#### getTask 方法 打印数据 ####

      getTask = (id, bucked) => {
        apis.getTask(id, bucked)
        .then(data => console.log(data))
        .catch(err => console.info(err))
  }

期望的数据是拿到的


然而 当我在 getTask方法中重新设置state时 在render中打印 失败

   getTask = (id, bucked) => {
    apis.getTask(id, bucked)
        .then(data => this.setState({data}))
        .catch(err => console.info(err))
  }

结果

render里打印的

 console.log(this.state.data)


为什么设置state失败呢

解决方案

代码本身没有问题,格式差,犯了一个低级错误.

这篇关于javascript - react willmount调用 promise .then拿到数据了 设置state失败?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆