异步/等待未按预期工作:ReactJS +异步等待

时间:2019-07-26 07:17:01

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

我在使用aysnc和await执行API调用时遇到问题。我正在使用一个数据网格,该数据网格具有data,column和每列的下拉选项集,以实现列过滤(我从服务器获取的data和下拉选项)。

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

获取此服务器的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}
        />
    );
  }
}


1 个答案:

答案 0 :(得分:1)

问题出在这一行:

/bin
上面的setTimeout(() => this.fetchData(response, stateObject), 2000); // Waiting for the ID to receive and then call fetchData 执行完毕后,应调用

this.setColumnData();。为此,您需要将setTimeout包装在Promise中:

setTimeout