繁体   English   中英

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

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

我正在学习 react-native,但遇到了一个问题。 为什么从异步函数获取数据返回一个承诺,但在异步函数本身中,它正确返回一个对象数组?

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

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

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

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

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

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

另一种类似于提问者原始代码的方法:

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

或者另一种方式是

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

这会将您的数据复制到不可变对象并重新指定名称,还将默认值设置为对象dataSource

暂无
暂无

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

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