首页 > 解决方案 > 当 json 在 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);
};

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

标签: jsonreact-nativefetch

解决方案


setState是异步的。

在您的代码中,您试图console.log在状态更新之前进行。

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

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

});

查看此帖子以获取更多信息或其他问题


推荐阅读