使用fetch w/react js访问返回promise中的对象

Accessing object in returned promise using fetch w/ react js

本文关键字:promise 返回 对象 访问 js fetch react 使用      更新时间:2023-09-26

我有这个函数:

  getUserData() {
    fetch(this.props.apiUrl + this.state.username + '?client_Id=' + this.props.clientId + '&client_secret=' + this.props.clientSecret)
      .then(function(response) {
        var data = response.json();
        this.setState({
          userData: data
        });
        console.log(this.state.userData);
      }.bind(this))
      .catch(function(error) {
        this.setState({
          username: null
        });
        console.log(error)
      }.bind(this)) 
  }

它在控制台中返回这个:

Promise{[[PromiseStatus]]:"挂起",[[PromiseValue]]:未定义}

原型[[PromiseStatus]]:"已解决"

[[PromiseValue]] : Object
avatar_url : "https://avatars.githubusercontent.com/u/"
login      : "hello world"
.
.
.

我需要访问对象中的名称/值对,但无法访问它们。我假设在将响应转换为json之后,我需要多走一步,但我无法弄清楚。如果有人能帮忙,我们将不胜感激!

response.json()返回一个promise,因此您还需要适当地处理它,例如:

.then(function(response) {
    return response.json();
})
.then(function(parsedData) {
    // data here
})

这里有一个处理json对象的更短的方法

fetch(endpoint, request)
.then(response => response.json())
.then(json => {
  //handle json response
}

只需使用await:response = await response.json();并且您将在响应中有对象,因此您必须首先将函数设置为asyncCCD_ 3和在获取之前使用wait。