【发布时间】:2018-06-11 18:26:46
【问题描述】:
我正在使用 React、TypeScript 和 axios 处理 HTTP 请求。 当我执行 axios.get (myURL) 时,我会以这种格式获取数据:
[["value1","value2"],["value3","value4"],["value5","value6"]]
我创建了一个代表字符串数组的类。代码如下:
import Serializable from '../interface/serializable';
export default class Row {
public row:string[];
}
这是我想在其中使用此类的组件的代码:
import Row from '../class/row';
interface IColumnSelectionState {
readonly data: Row[],
}
class MyDataextends React.Component<any,IColumnSelectionState>{
constructor(props: any) {
super(props);
this.state = {
data: [],
}
this.submit = this.submit.bind(this);
}
private submit():void{
axios.get("myURL").then(res => {
const response = res.data;
this.setState({ data: response });
}).catch(error => {
console.log(error);
})
}
}
我执行“submit()”方法时的问题:
console.log (this.state.data) // I see my data in the format described above
但是当我这样做时:
console.log (this.state.data [0].row) // this shows me undefined while I declared my array in the Row class
我真的需要得到第一个数组来循环它并进行处理。
如果有人知道如何做到这一点,谢谢你的帮助!
提前谢谢你!!!
【问题讨论】:
-
是否需要在构造函数中初始化'this.state.data'?如果是这样,您应该为其分配一个新的 Row[],而不是 []。
标签: reactjs typescript axios