首页 > 解决方案 > 在 React 中调用 API 后设置状态

问题描述

我正在尝试在 API 调用后设置状态。我正在循环通过 fetch 调用来检索数据,但由于某种原因,如果我 console.log(this) 它将在 this.state.data 中显示我的数据,但如果我 console.log(this.state.data) 或 (this .data) 我有一个空数组。

 fetchData = (url, index) => {
      fetch(url + index * 100)
      .then(response => response.json())
        .then(result => 
          this.setState({
            data: result
          }))}





searchChar = () => {
      this.setState({
        loaded: true,
        logo: false,
        notFound: false,
      })

      let value = this.state.basicAddon1.toLowerCase();
      const foundSearch = [];
      const comics = [];
      const url = this.state.url;
      const offsetLimit = 5;
      const searchIndex = value.charAt(0)  
      let searchUrl = url.replace("tempKey", searchIndex);


          for(let apiSearch = 0; apiSearch < offsetLimit; apiSearch++){
            this.fetchData(searchUrl, apiSearch);

console.log(this) - Gets data back if I search the log and go to state and data
console.log(this.state) - Gets undefined 
console.log(this.data) - Get undefined





标签: javascriptreactjs

解决方案


所以这里实际上发生了一些事情。

首先,注意你是如何设置this.state.data结果的。这意味着每次运行此函数时,this.state.data都会被覆盖。您可能希望将数据转换为对象列表。

其次,注意fetchData使用 fetch 是异步的。这意味着该函数在返回之前不会等待获取完成。所以会发生什么,在你的循环中,函数运行了几次,在setState被调用之前,你正在记录。要解决此问题,请等待所有数据解决后再继续。

获取数据

fetchData = async (url, index) => {
  await fetch(url + index * 100)
  .then(response => response.json())
  .then(result => 
      this.setState({
        data: result // You may want to the replace this line considering the first issue
       })
    )
}

搜索字符

searchChar = async () => {
   ...

   var dataFetchPromises = []
   for(let apiSearch = 0; apiSearch < offsetLimit; apiSearch++){
        dataFetchPromises.push(this.fetchData(searchUrl, apiSearch))

    await Promise.all(dataFetchPromises)

   ...
}

推荐阅读