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

妖精的绣舞 提交于 2020-05-24 18:15:47

问题


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?

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;
  }

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}

... 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?


回答1:


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),
      })  
    });
}



回答2:


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),
    })  
  }



回答3:


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



来源:https://stackoverflow.com/questions/45200723/react-native-async-function-returns-promise-but-not-my-json-data

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!