简体   繁体   English

react-native async 函数返回promise 但不返回我的json 数据?

[英]react-native async function returns promise but not my json data?

I'm learning react-native, and I'm running into an issue.我正在学习 react-native,但遇到了一个问题。 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?为什么从异步函数获取数据返回一个承诺,但在异步函数本身中,它正确返回一个对象数组?

On componentDidMount() , I call my async function which in turn does a fetch to an api url:componentDidMount() ,我调用我的 async 函数,该函数反过来获取一个 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;
  }

In console.log(json) , I get the correct list of json objects, and I can access them with json[0].name .console.log(json) ,我得到了正确的 json 对象列表,我可以使用json[0].name访问它们。 But later, console.log(data) returns a promise with odd data:但后来, console.log(data)返回一个带有奇数数据的承诺:

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

... and I can no longer find my json objects. ...我再也找不到我的 json 对象了。 Why is this?这是为什么? More importantly, how can I retrieve my json data in componentDidMount() so that I can set it as the dataSource ?更重要的是,如何在componentDidMount()检索我的 json 数据,以便将其设置为dataSource

Since getData() is a promise, you should be able to obtain the data in a then block as follows:由于getData()是一个承诺,您应该能够在then块中获取数据,如下所示:

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

Another approach similar to the original code of the questioner:另一种类似于提问者原始代码的方法:

async componentDidMount() {
    let data = await this.getData();
    console.log(data);    
    this.setState({
      dataSource:this.state.dataSource.cloneWithRows(data),
    })  
  }

Or another way is或者另一种方式是

  async componentDidMount() {
    const { data: dataSource = [] } = await this.getData();   
    this.setState({dataSource})  
  }

This will copy your data to a inmutable object an reasign the name, also, set a default value to the object dataSource这会将您的数据复制到不可变对象并重新指定名称,还将默认值设置为对象dataSource

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM