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

新手上路,请多包涵

我有这个功能:

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

在控制台中返回这个:

承诺 {[[PromiseStatus]]: “pending”, [[PromiseValue]]: undefined}

proto [[PromiseStatus]]:“已解决”

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

我需要访问对象中的名称/值对,但我无法访问它们。我假设在将响应转换为 json 但无法弄清楚之后我需要采取额外的步骤。如果有人可以提供帮助,将不胜感激!

原文由 Banner 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 222
2 个回答

response.json() 返回一个承诺,所以你还需要适当地处理它,例如:

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

原文由 zerkms 发布,翻译遵循 CC BY-SA 3.0 许可协议

这是处理 json 对象的更短方法

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

原文由 Jordan Hochstetler 发布,翻译遵循 CC BY-SA 3.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题