React js在for循环中使用axios填充贴图



我试图在react js项目中可视化一个折线图(使用canvas js(,所以我使用axios get请求获得一个数据,并循环此请求来填充一个用作折线图输入的数据变量,但我的问题是axios似乎随机填充我的数据

这是我在componentdidmount():中的代码

constructor(props) {
super(props);
this.state = {
data: [] ,
};
}
componentDidMount(){
let responses = []
for (let i = 0; i < 8; i++) {
responses.push(axios.get("http://localhost:5000/transfer/getUsesByDay/"+i).then(res =>{
return res.data
}))
}
Promise.all(responses).then(results => {
console.log(results)
this.setState(prevState => {
return {
data: [...prevState.data, ...results.map(r => r)]

};
})
}
)

这就是渲染函数:

render() {
const { data: chartData } = this.state;
const { classes } = this.props;
{console.log(chartData)}
return (
<Paper>
<Chart
data={chartData}
className={classes.chart}
>

现在,当我执行时,我得到了这个结果(console.log(results((:

0: {year: "15", utilisation: 3}
1: {year: "12", utilisation: 0}
2: {year: "12", utilisation: 0}
3: {year: "09", utilisation: 1}
4: {year: "08", utilisation: 1}
5: {year: "10", utilisation: 5}
6: {year: "09", utilisation: 1}
7: {year: "10", utilisation: 0}

然后,当我重新执行时,我得到了另一个类似的结果:

0: {year: "11", utilisation: 3}
1: {year: "10", utilisation: 0}
2: {year: "10", utilisation: 0}
3: {year: "09", utilisation: 1}
4: {year: "09", utilisation: 1}
5: {year: "09", utilisation: 5}
6: {year: "08", utilisation: 1}
7: {year: "08", utilisation: 0}

结果应该这样排序:

0: {year: "14", utilisation: 3} // the result of http://localhost:5000/transfer/getUsesByDay/"+i when i == 0 , and so on
1: {year: "13", utilisation: 0}
2: {year: "12", utilisation: 0}
3: {year: "11", utilisation: 1}
4: {year: "10", utilisation: 1}
5: {year: "09", utilisation: 5}
6: {year: "08", utilisation: 1}
7: {year: "07", utilisation: 0}

在您的问题中,您已经写道您正在进行

console.log(res.data) 

但这在代码中是不可见的。通过猜测,我可以看到你在中使用了res变量名

then(res =>{
return res.data
})

如果您在上面的语句中执行了console.log,那么它将取决于每个调用的响应,并且每次输出的顺序可能是随机的。

由于互联网上发生了一些事情(数据丢失,必须再次发送,等等(,您的一些响应是后一个响应,甚至是先请求的。

最新更新