繁体   English   中英

无法在反应中设置状态

[英]Can't set state in react

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

你做错了两件事。

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

这应该有效。

不要改变状态。

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM