当json fetch in native本机时获取未定义

Ste*_*fey 6 json fetch react-native

在我下面的简化代码中,我能够以JSON格式提取数据,但如果我尝试控制对象的特定键的控制台,我将得到未定义.

我以为我可以this.state.profile.name用来显示"史蒂文".undefined当我能够看到整个响应时,为什么会出现这种情况?谢谢!

state = {
responseJSON: null,
};
callGraph = async token => {

const response = await fetch(
  `https://graph.facebook.com/me?access_token=${token}&fields=id,name,email,about,picture`
);
const responseJSON = JSON.stringify(await response.json());

  this.setState({ 
    profile: responseJSON
  });

console.log("profile = " + this.state.profile);
};
Run Code Online (Sandbox Code Playgroud)

console.log输出如下:

profile = {"id":"*******","name":"Steven *******","email":"steve@*******.com","picture":{"data":{"height":50,"is_silhouette":false,"url":"https://platform-lookaside.fbsbx.com/platform/profilepic/?asid=*******&height=50&width=50&ext=1539943832&hash=AeQM2VfUBmdfOVJZ","width":50}}}
Run Code Online (Sandbox Code Playgroud)

Kev*_*off 4

setState是异步的。

在您的代码中,您尝试console.log在状态更新之前执行此操作。

您需要使用回调作为函数的第二个参数setState

 this.setState({ 
    profile: responseJSON
  }, () => {
console.log("profile = " + this.state.profile);

});
Run Code Online (Sandbox Code Playgroud)

查看这篇文章以获取更多信息或其他问题