映射函数内部异步调用后如何更新状态?

时间:2018-08-15 02:20:27

标签: javascript reactjs axios

我正在尝试获取从axios get方法返回到aon对象的方法调用的数据。而不是返回值,而是在返回承诺。我在这里想念什么?

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);

这是指向codesandbox

的链接

注意:这只是参考代码。我无法执行setState,因为我正尝试从 array.map()迭代器调用该方法。

编辑:

这实际上是我想要做的:codesandbox.io/s/n5m3qyn65l

出于某种原因,它显示了Network Error

感谢您的帮助。

3 个答案:

答案 0 :(得分:0)

setState得到回应后,您应该fetchData(),因为fetchData()将返回您在状态中设置的promise。

请记住,setState仅做分配,您不能期望它等待异步操作。在这种情况下,请尝试async/await

更新后的答案:

https://codesandbox.io/s/1r22oo804q

找到内嵌评论

答案 1 :(得分:0)

在更新文章之前,您应该使用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))

答案 2 :(得分:0)

// 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();               
        }