我刚刚开始学习 React,所以请记住这一点。我正在尝试使用 fetch 从公共(public) 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)'
]
}
]
}
});
}
最佳答案
您应该在then function
内设置状态您的 API 调用的,使用 componentDidMount()
是一个很好的做法进行 ajax 调用时的生命周期钩子(Hook)
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");
});
}
关于javascript - React 新手 - 使用 Fetch,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49518426/