[英]How to update state after an async call inside a map function?
我正在尝试获取从axios get方法返回到on对象的方法调用的数据。 而不是返回值,而是在返回承诺。 我在这里想念什么?
import React, { Component } from "react";
import ReactDOM from "react-dom";
import axios from "axios";
import "./styles.css";
class App extends Component {
state = {
totalResults: ""
};
componentDidMount() {
this.setState({
totalResults: this.fetchData()
.then(function(res) {
const r = res.data.totalResults;
return r;
})
.catch(err => console.log("error: ", err))
});
}
fetchData = () => {
return axios.get(
"https://newsapi.org/v2/top-headlines?country=us&apiKey=8d98dac05ec947d1b891832495641b49"
);
};
render() {
return (
<div className="App">
<h1>Hello CodeSandbox</h1>
<button onClick={() => console.log(this.state.totalResults)}>
Click
</button>
</div>
);
}
}
const rootElement = document.getElementById("root");
ReactDOM.render(<App />, rootElement);
这是codeandbox的链接
注意:这只是参考代码。 我无法执行setState,因为我正尝试从array.map()迭代器调用该方法。
编辑:
这实际上是我要尝试执行的操作: codesandbox.io/s/n5m3qyn65l
由于某种原因,它显示Network Error
谢谢你的协助。
从fetchData()
获得响应后,应设置setState
,因为fetchData()
将返回您在状态中设置的promise。
请记住, setState
仅会执行分配,您不能期望它等待异步操作。 在这种情况下,请尝试async/await
更新的答案:
https://codesandbox.io/s/1r22oo804q
查找内嵌评论
在更新文章之前,应使用Promise.all()
来获取所有图像。 像这样:
const res = response.data;
Promise.all(res.map(article => (
this.fetchImages(article.featured_media)
.then(image => ({
title: article.title.rendered,
content: article.content.rendered,
featuredImage: image.guid.rendered
}))
.catch(err => console.log("Error fetching image: ", err))
))
)
.then(articles => this.setState({ articles }))
.catch(err => console.log("Error setting up articles: ", err))
// Our basic components state setup
class myComponent extends Component {
constructor(props) {
super(props);
this.state = {
currentSession: {
fullNames: [],
contactInfo: []
}
}}
// Here we make our function to fetch our API data
fetchData()
.then(res => {
let namesData = res.data.name;
let contactData = res.data.email;
this.setState(prevState => ({
currentSession: {
...prevState.currentSession,
fullNames: Object.assign(namesData),
contactInfo: Object.assign(contactData)
}
}));
});
// Since it's an async call, we'll put in in a 'componentDidMount' method
componentDidMount() {
this.fetchData();
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.