[英]How can I properly read json data from ajax response?
I did something like this: 我做了这样的事情:
axios.get(url).then(result => {
this.setState({
list: result.data,
});
})
.catch(e => {
console.log("Some error", e);
});
Constructor looks like this: 构造函数如下所示:
constructor(props: any) {
super(props);
this.state = {
list: [],
};
}
I want to put it somewhere and check whether it works: 我想将它放在某个地方,然后检查它是否有效:
const {fetchedData}: any = this.state;
const data: IScheduler = fetchedData.list;
but I get uncaught TypeError: cannot read property 'list' of undefined... 但我遇到了TypeError:无法读取未定义的属性'list'...
It works when I do that this way: 当我这样做时,它会起作用:
const data: IScheduler = {
generatedDate: "03.12.2017";
subjects: [
....
],
};
But it's not the point. 但这不是重点。 What am I doing wrong?
我究竟做错了什么? How should I fix it?
我应该如何解决? Can somebody help me?
有人可以帮我吗?
In your state there is no property fetchedData
. 在您的状态下,没有属性
fetchedData
。 You set your list to this.state.list, not to this.state.fetchedData.list
. 您将列表设置为this.state.list,而不是
this.state.fetchedData.list
。 So you need to change your code from: 因此,您需要从以下位置更改代码:
const {fetchedData}: any = this.state;
const data: IScheduler = fetchedData.list;
to: 至:
const {list}: any = this.state;
const data: IScheduler = list;
It should work. 它应该工作。 If you really want your first data structure you need to change your default state structure and
setState
, but nested data structure is not recommended . 如果确实需要第一个数据结构,则需要更改默认状态结构和
setState
,但不建议嵌套数据结构 。
axios.get(url).then(result => {
this.setState({
fetchedData: {
list: result.data
}
});
})
.catch(e => {
console.log("Some error", e);
});
Constructor should looks like this: 构造函数应如下所示:
constructor(props: any) {
super(props);
this.state = {
fetchedData: {
list: []
}
};
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.