javascript - 在变量中从 REST API 传递 GET 答案 - React.js
问题描述
我对反应有点新。我在 go 中制作了一个 REST API,它发送这样的 JSON
[{Key1: value1, Key2: value2},{Key1: value3, Key2: value4},{Key1: value5, Key2: value6}]
调用 API 的 react 组件如下所示
import React from "react";
import axios from "axios";
class State extends React.Component {
constructor(props) {
super(props);
this.state={
graph_data:[{
Indication: '',
IsOpen: '',
Number: 0
}],
};
}
componentDidMount() {
const res=[]
axios.get('http://127.0.0.1:8080/watch/1.0.0/state')
.then(response => {
for(let x = 0; x < response.data.length; x++) {
res[x] = response.data[x];
console.log(res[x])
}
});
console.log(res[2])
}
render() {
const { graph_data } =this.state.graph_data;
return (
<div className="graph-wrapper">
<div className="graph">
<h3>{ graph_data }</h3>
</div>
</div>
)
}
}
export default State;
graph_data 中的值<h3></h3>
是空的,如何让它获取 JSON 数据?console.log(res[x]) 向我显示 x 值处的列表值,但之后的 console.log(res[2]) 为空 谢谢