我在 React 中使用 axios 调用的经验不是很丰富,我正在尝试进行 axios 调用来获取一个数组,然后使用该数组为数组中的每个项目进行 axios 调用。我从第一次调用中获取数组,然后从每个单独的调用中获取对象数组,但在状态更新后,没有任何内容呈现。这是我的代码:
我尝试使用单独的方法来更新对象数组的状态,但这不起作用。
state = {
items: [],
searchItem: "newstories",
promises: [{}]
};
componentDidMount() {
const { searchItem } = this.state;
axios
.get(
"https://hacker-news.firebaseio.com/v0/" +
this.state.searchItem +
".json?print=pretty"
)
.then(result => {
const topStories = result.data;
this.setState({ topStories });
let promises = [];
for (let i = 0; i < topStories.length; i++) {
axios
.get(base + topStories[i] + extension)
.then(res => {
const newItem = res.data;
promises.push(newItem.title);
})
.catch(error => console.log("Something went wrong"));
}
// Set the state of the array of objects
this.setState({ promises });
});
}
render() {
let counter = 0;
return (
<div>
{this.state.promises.map(stories => (
<li style={{ listStyle: "none" }} key=stories.id>
{(counter += 1)}. {stories.title}
</li>
))}
</div>
);
}
}
我希望能够映射和获取每个对象并相应地使用每个对象的属性。每个对象看起来像这样:
{作者:“thinksocrates”id:20004127 child :[…] 得分:28 标题:“OKR”}
渲染没有返回任何标题,但在状态更改后我可以在控制台日志中看到它们,所以我不确定发生了什么。我猜测我错误地获取了 promise 数组,但我不确定如何在这种情况下使用 axios.all 。
最佳答案
this.setState({ Promise });
将在所有 Promise 解决之前运行。这是解决问题的更好方法。
.then(result => {
const topStories = result.data;
const promises = topStories.map(story => {
return axios.get(base + story + extension).then(res => res.data)
})
Promise.all(promises).then(data => {
console.log(data)
this.setState({ promises: data })
})
更改渲染
render() {
return (
<div>
{this.state.promises.map((stories, index)=> (
<li style={{ listStyle: "none" }} key=stories.id>
{`${index + 1}}.${stories.by}`}
</li>
))}
</div>
);
}
关于reactjs - 单独的 Axios 调用数组中的每个项目,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56319625/