react-native异步函数返回promise但不是我的json数据? [英] react-native async function returns promise but not my json data?

查看:315
本文介绍了react-native异步函数返回promise但不是我的json数据?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在学习本机响应,但是遇到了问题.为什么从异步函数返回时获取数据会返回一个Promise,但在异步函数本身中,它会正确返回一个对象数组?

I'm learning react-native, and I'm running into an issue. Why does getting data on return from an async function return a promise, but in the async function itself, it correctly returns an array of objects?

componentDidMount()上,我调用了我的异步函数,该函数依次提取到api网址:

On componentDidMount(), I call my async function which in turn does a fetch to an api url:

  componentDidMount() {
    let data = this.getData();
    console.log(data);    // <-- Promise {_40: 0, _65: 0, _55: null, _72: null}
    this.setState({
      dataSource:this.state.dataSource.cloneWithRows(data),
    })  
  }

  async getData() {
    const response = await fetch("http://10.0.2.2:3000/users", {
            method: 'GET',
            headers: {
                'Accept': 'application/json',
                'Content-Type': 'application/json',
            }   
        }); 
    const json = await response.json();
    console.log(json);     // <-- (5) [Object, Object, Object, Object, Object]
    return json;
  }

console.log(json)中,我获得了json对象的正确列表,并且可以使用json[0].name访问它们.但是后来,console.log(data)返回一个带有奇数数据的promise:

In console.log(json), I get the correct list of json objects, and I can access them with json[0].name. But later, console.log(data) returns a promise with odd data:

Promise {_40: 0, _65: 0, _55: null, _72: null}

...,我再也找不到我的json对象.为什么是这样?更重要的是,如何在componentDidMount()中检索我的json数据,以便可以将其设置为dataSource?

... and I can no longer find my json objects. Why is this? More importantly, how can I retrieve my json data in componentDidMount() so that I can set it as the dataSource?

推荐答案

由于getData()是一个承诺,因此您应该能够在then块中获取数据,如下所示:

Since getData() is a promise, you should be able to obtain the data in a then block as follows:

componentDidMount() {
  this.getData()
    .then((data) => {
      this.setState({
        dataSource:this.state.dataSource.cloneWithRows(data),
      })  
    });
}

这篇关于react-native异步函数返回promise但不是我的json数据?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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