【问题标题】:Can't set state in react无法在反应中设置状态
【发布时间】:2026-01-05 13:50:02
【问题描述】:

所以,我只是想在我的 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);
      });
  };

【问题讨论】:

标签: javascript reactjs axios es6-promise


【解决方案1】:

你做错了两件事。

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

【讨论】:

  • 如果您的代码示例不可运行,请不要使用可运行堆栈 sn-p。您可以通过缩进 4 个空格或用 3 个反引号包围代码来创建格式化代码块。
  • 另外,在第二个示例中,您在getPics 函数中使用了Category,它可能应该是cat
  • @EmileBergeron 对。我只是想让 OP 知道如何做到这一点。顺便谢谢,让我解决这个问题
  • @EmileBergeron 更新了答案
【解决方案2】:

这应该可行。

不要改变状态。

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

【讨论】:

  • 不是我对你投了反对票,但我认为你应该添加一个解释你的代码的作用。 Stack Overflow 通常不喜欢纯代码的答案。
  • 非常感谢,这段代码确实有效,虽然我对 async/await 有很好的理解,但我不确定为什么会这样,我一直在尝试将这个概念应用于我的其他函数( TopStories()) 但我不知道如何实现,因为我不是 100% 知道它是如何工作的。但它确实如此,谢谢你,所以它得到了我的支持:)
最近更新 更多