我刚开始学习反应所以请记住这一点。我试图使用fetch从公共API中提取数据,然后将其放在"标签" setState里面的部分。我正在使用chart.js所以我正在寻找标签,以便根据api收集纽约市五个行政区的数组。问题是在fetch和setState之间传输数据。我能够很好地获取数据。我已经尝试了一些事情,并希望得到任何帮助
constructor(){
super();
this.state = {
chartData:{},
}
}
componentWillMount(){
this.getChartData();
}
getChartData(){
// Ajax calls here
fetch("https://data.cityofnewyork.us/resource/27iv-9uub.json")
.then(response => response.json())
.then(data => {
// eslint-disable-next-line
let boroughs = data.map((data) => {
console.log(data.borough);
return data.borough;
})
console.log(boroughs);
return boroughs;
})
.catch(() => {
console.log("Promise Rejected");
});
let labels = boroughs;
console.log(labels, 'test');
this.setState({
chartData:{
labels: labels,
datasets:[
{
label:'Population',
data:[
617594,
1810450,
153060,
106519,
105162
],
backgroundColor:[
'rgba(255, 99, 132, 0.6)',
'rgba(54, 162, 235, 0.6)',
'rgba(255, 206, 86, 0.6)',
'rgba(75, 192, 192, 0.6)',
'rgba(153, 102, 255, 0.6)',
'rgba(255, 159, 64, 0.6)'
]
}
]
}
});
}
答案 0 :(得分:3)
您应该在API调用的then function
内设置状态,在进行ajax调用时使用componentDidMount()
生命周期挂钩是个好习惯
constructor(){
super();
this.state = {
chartData:{},
}
}
componentDidMount(){
this.getChartData();
}
getChartData(){
// Ajax calls here
fetch("https://data.cityofnewyork.us/resource/27iv-9uub.json")
.then(response => response.json())
.then(data => {
// eslint-disable-next-line
let boroughs = data.map((data) => {
console.log(data.borough);
return data.borough;
})
this.setState({
chartData:{
labels: boroughs,
datasets:[
{
label:'Population',
data:[
617594,
1810450,
153060,
106519,
105162
],
backgroundColor:[
'rgba(255, 99, 132, 0.6)',
'rgba(54, 162, 235, 0.6)',
'rgba(255, 206, 86, 0.6)',
'rgba(75, 192, 192, 0.6)',
'rgba(153, 102, 255, 0.6)',
'rgba(255, 159, 64, 0.6)'
]
}
]
}
});
})
.catch(() => {
console.log("Promise Rejected");
});
}
答案 1 :(得分:2)
在这种特殊情况下,需要在承诺成功时接收数据的this.setState
内调用then
。
所以,像这样:
fetch("https://data.cityofnewyork.us/resource/27iv-9uub.json")
.then(response => response.json())
.then(data => {
this.setState({...});
return data;
})
.catch(() => {
console.log("Promise Rejected");
});
这里的根本问题是,在boroughs
回调中解除承诺之前,您没有then
。
答案 2 :(得分:0)
将此行放在this.getChartData = this.getChartData.bind(this);
{{1}}