【问题标题】:Async/Await is not working as expected : ReactJS+ Async AwaitAsync/Await 没有按预期工作:ReactJS+ Async Await
【发布时间】:2019-12-04 11:57:58
【问题描述】:

我在使用 aysnc 和 await 执行 API 调用时遇到问题。我正在使用一个数据网格,其中包含数据、列和每列的一组下拉选项来实现列过滤(我从服务器获取的数据和下拉选项)。

列配置数组依赖于这些选项,其中每列都标记有与其对应的选项。我已将此列过滤器提取为一个单独的组件,并在其中传递此选项。

对该服务器的 Fetch API 调用的工作方式是,每次查询时我都会获得一个 ID,然后将该 ID 传递给下一个函数以获取实际数据。

所以我先查询表格数据,然后获取下拉值,然后设置列对象,以便表格正确呈现。

但这里的问题是,按照我编写代码的方式,它应该可以正常工作。但是,当我刚刚加载页面时,它在 getColumnFilterValues 中出现错误,提示“无法读取未定义的参数”。使用 async/await 下拉值应该在设置列数据之前可用。但就我而言,它会引发上述错误。

有人能说出这里出了什么问题吗?


import * as React from "react";
const FETCH_ID_URL = "/fetch/id";
const FETCH_DATA_URL = "/fetch/data";


export default class Test extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      data: [], // hold table data
      columns: [], // hold column config
      dropDownValues: [], // hold column filter dropdown values
    };
  }

  async componentDidMount() {
    await this.fetchTableData(); // First fetching the table data
    await this.fetchDropDownValues(); // fetching the dropdown values for each column  
    this.setColumnData();  // then setting column object which is dependent on dropdown values
  }

  fetchDropDownValues = async () => {
    await this.fetchID(FETCH_ID_URL, payload, "dropDownValues");
  };

  fetchTableData = async () => {
    await this.fetchID(FETCH_ID_URL ,payload, "data");
  };

  fetchID = async (url, body, stateObject) => {
    try {
          const config = {
                          method: 'POST',
                          body: JSON.stringify(data)
                         }

         let response = await  fetch( url: FETCH_ID_URL, config);
         setTimeout(() => this.fetchData(response, stateObject), 2000); // Waiting for the ID to receive and then call fetchData
    } catch (e) {
      console.log(e);
    }
  };

  fetchData = async(obj: any, stateObject: string) => {
    try {
          const config = {
                          method: 'POST',
                          body: JSON.stringify(obj.id)
                         }
         let response = await  fetch( url: FETCH_DATA_URL, config);
         if (stateObject === "dropDownValues") {
           this.setState({ [stateObject]: response.dropdownData});
         } 
         else 
         {
            this.setState({[stateObject]: response.tableData});
         }
    } catch (e) {
      console.log(e);
    }
  };

  getValuesFromKey = (param: string) => {
    let data: any = this.state.dropDownValues[param]; //Throwing error here , giving cant read param of undefined
    let result = data.map((value: any) => {
      let keys = Object.keys(value);
      return {
        field: keys[0],
        checked: false,
      };
    });
    return result;
  };


  setColumnData = () => {
     let columns = [
      {
        Header: () => (
          <div>
              <Child
                name="firstName"
                options={this.getValuesFromKey("firstName")}
              />
            <span>First Name</span>
          </div>
        ),
        accessor: "firstName"
      },
      {
        Header: () => (
          <div>
              <Child
                name="status"
                options={this.getValuesFromKey("status")}
              />
            <span>Status</span>
          </div>
        ),
        accessor: "status",
      }
    ];
    this.setState({ columns });
  };

  render() {
    let { data, columns } = this.state;
    return (
       <ReactTable
          data={data}
          columns={columns}
        />
    );
  }
}


【问题讨论】:

  • 我不确定到底是什么问题,但创建一个 Promise 并实际返回它可能会有所帮助。
  • 问题出在 setTimeout 上。 Here看看这个讨论,你会从中得到更多的见解。

标签: javascript reactjs ecmascript-6 async-await setstate


【解决方案1】:

问题出在这一行:

setTimeout(() => this.fetchData(response, stateObject), 2000); // Waiting for the ID to receive and then call fetchData

this.setColumnData(); 应该在上面的setTimeout 执行完毕后调用。为此,您需要将setTimeout 包装在Promise 中:

return new Promise(resolve => {
  setTimeout(async () => {
    await this.fetchData(response, stateObject);
    resolve();
  }, 2000);
});

【讨论】:

    猜你喜欢
    • 2021-03-11
    • 2020-03-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-09-25
    • 1970-01-01
    • 2020-03-25
    • 1970-01-01
    相关资源
    最近更新 更多