【发布时间】:2019-06-17 15:25:12
【问题描述】:
我知道如何使用 reactJS store,但是当我将 store 与对象数组一起使用时遇到了问题。
constructor(props) {
super(props);
this.state = {
array: [{ id: null, summary: "", name: "" }]
};
}
componentWillMount() {
const query = "http://api.tvmaze.com/search/shows?q=game";
var dataCount;
axios.get(query).then(response => {
dataCount = response.data.length;
});
axios.get(query).then(response => {
for (let i = 0; i < dataCount; i++) {
if (response.status) {
this.setState({
array: [
...this.state.array,
{
id: i,
summary: response.data[i].show.summary,
name: response.data[i].show.name
}
]
});
}
}
});
}
实际上,我确实编写了此代码,但存在很多问题。它是 在 this.state.array[0] 中存储 array[0] 8-9 次。当我写 console.log(this.state.array[0]) 它不只打印一个实例。 始终打印有关 axios GET 方法响应计数次数的对象。 我想存储像 this.state.array[0]={id:1, summary:"xyz",name:"abc"}, this.state.array1={id:1, summary:"xyz", name:" abc"}。
【问题讨论】:
-
为什么要发送两个axios请求?
-
一个是获取数据计数,另一个是使用 for 循环获取数据。但你是对的,一个就足够了
-
您不必对两个请求执行此操作。它们都是异步运行的,所以不能保证在解析第二个时,
dataCount的值不是undefined。把它们放在一起。
标签: reactjs react-native store