无法在反应中设置状态

时间:2020-01-16 18:22:15

标签: javascript reactjs axios es6-promise

所以,我只是想在我的应用程序中设置状态。只需从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);
      });
  };

2 个答案:

答案 0 :(得分: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 });
  };

getPics = cat => {
      return axios
            .get(
              "https://api.pexels.com/v1/search?query=" +
                cat +
                "&per_page=15&page=1",
              {
                Authorization:
                  "563492ad6f91700001000001d33b5d31a9a145b78ee67e35c8e6c321"
              }
            )
            .then(res => {
              return { [cat]: res.photos[0].src.large2x };
            });

}

GeneratePic = async () => {
        const promises = this.state.Catogories.map(Catogory => {
          this.getPics(Catogory);
        });
        
        let photos = await Promise.all(promises);
        this.setState({ CatPics: photos });
      };

答案 1 :(得分:-1)

这应该有效。

不要改变状态。

 GeneratePic = () => {
        this.state.Catogories.forEach(async Catogory => {
            await axios
                .get(
                    "https://api.pexels.com/v1/search?query=" +
                    Catogory +
                    "&per_page=15&page=1", {
                        Authorization: "563492ad6f91700001000001d33b5d31a9a145b78ee67e35c8e6c321"
                    }
                )
                .then(res => {
                    var object = { Catogory: res.data.photos[0].src.large2x };
                    const cPics = [...this.state.CatPics];
                    cPics.push(object);
                    this.setState({
                        CatPics: cPics
                    })
                });
        });
    };