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)
setState
是异步的。
在您的代码中,您尝试console.log
在状态更新之前执行此操作。
您需要使用回调作为函数的第二个参数setState
:
this.setState({
profile: responseJSON
}, () => {
console.log("profile = " + this.state.profile);
});
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
587 次 |
最近记录: |