无法设置反应状态

问题描述 投票:-1回答:2

所以,我只是试图在我的应用程序中设置状态。只需从Axios获取数据,然后设置状态即可。但是无论我做什么,状态都不会设置。我已经尝试将其放入回调中,因为它是异步的,并且将其放置在组件上并且组件没有更新。有指针吗?

class App extends Component {
  componentDidUpdate() {}

  constructor(props) {
    super(props);
    this.state = {
      Catogories: [
        "Business",
        "Entertainment",
        "General",
        "Health",
        "Science",
        "Sports",
        "Technology"
      ],
      CatPics: [],
      TopStories: [],
      Selection: [],
      Sources: [],
      selected: false
    };
  }
  GeneratePic = () => {
    this.state.Catogories.forEach(Catogory => {
      axios
        .get(
          "https://api.pexels.com/v1/search?query=" +
            Catogory +
            "&per_page=15&page=1",
          {
            Authorization:
              "563492ad6f91700001000001d33b5d31a9a145b78ee67e35c8e6c321"
          }
        )
        .then(res => {
          var object = { Catogory: res.photos[0].src.large2x };
          this.state.CatPics.push(object);
        });
    });
  };
  dump = x => {
    this.setState({ TopStories: x }, console.log(this.state.TopStories));
  };
  TopStories = () => {
    console.log("working");
    axios
      .get(
        "https://newsapi.org/v2/top-headlines?country=us&apiKey=91bec895cf8d45eaa46124fb19f6ad81"
      )
      .then(res => {
        console.log(res);
        const data = res.data.articles;
        console.log(data);
        this.dump(data);
      });
  };
javascript reactjs axios es6-promise
2个回答
2
投票

您做错了两件事。

  1. 不要改变状态
  2. 不要在循环中执行异步操作,然后在异步回调中使用相同的循环变量,因为在那个时间点,循环变量将具有其他值,而不是各自的迭代类别。
  GeneratePic = async () => {
    const promises = this.state.Catogories.map(Catogory => {
      return axios
        .get(
          "https://api.pexels.com/v1/search?query=" +
            Catogory +
            "&per_page=15&page=1",
          {
            Authorization:
              "563492ad6f91700001000001d33b5d31a9a145b78ee67e35c8e6c321"
          }
        )
        .then(res => {
          return res.photos[0].src.large2x;
        });
    });

    let photos = await Promise.all(promises);
    photos = this.state.Catogories.map((cat, index) => ({ [cat]: photos[index] }));
    this.setState({ CatPics: photos });
  };

-1
投票

React中的状态是不可变的,只能通过setState方法更改它。我在下面使用的语法创建了一个CatPics副本,并将其连接到带有对象的新数组中。它称为destructuring

this.setState({ CatPics: [...this.state.CatPics, object] });
© www.soinside.com 2019 - 2024. All rights reserved.