我无法从以下反应代码的图形输出中提取name变量。试图将从api收到的json输出中的名称值存储在React的状态变量中。我该怎么做?
state = {
auth: false,
username: '',
access_token: '',
app_name: [],
};
responseFacebook = response => {
{/*console.log(response);*/}
if(response.status !== 'unknown')
this.setState({
auth: true,
username: response.name,
access_token: response.accessToken
});
graph.setAccessToken(this.state.access_token);
graph.get("/me/accounts", function(err, res) {
let response = res;
console.log(response.data[0]);
});
console.log(this.state);
}
可能是因为您在回调之外检查第二个console.log
。在javascript中,回调(get调用内部的函数)稍后触发,当API完成时,因此你不会在回调之外的console.log
中获得任何东西,如果你重写你的例子,它可能会工作。
state = {
auth: false,
username: '',
access_token: '',
app_name: [],
};
responseFacebook = response => {
if(response.status !== 'unknown') {
this.setState({
auth: true,
username: response.name,
access_token: response.accessToken
});
graph.setAccessToken(this.state.access_token);
graph.get("/me/accounts", (err, res) => {
let response = res;
this.setState({username:response.data[0]});
console.log(this.state);
});
}
}
事件循环引用