在下面的简化代码中,我能够提取JSON格式的数据,但是如果我尝试控制台记录该对象的特定键,则无法定义。
我曾经以为我可以使用this.state.profile.name
来显示“ Steven”。
当我能够看到整个响应时,为什么会显示为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}}}
答案 0 :(得分:4)
setState
是异步的。
在您的代码中,您尝试在状态更新之前console.log
。
您需要将回调用作setState
函数的第二个参数:
this.setState({
profile: responseJSON
}, () => {
console.log("profile = " + this.state.profile);
});
检查this post以获得更多信息,或者也检查this other question
答案 1 :(得分:2)
setState是异步的。凯文的答案是完全正确的。但是,您也可以使用此方法立即查看结果:
this.profile= responseJSON;
console.log("profile = " + this.profile);
您还应该像这样在构造函数中定义它:
constructor(props) {
super(props);
this.profile='';
}
此外,要访问屏幕中的配置文件参数,您需要使用this.profile
。