如何先从 Api 获取数据,然后调用 my 函数?

How to get data from Api first and then call the my function?

我有一个在 kendo 网格中分组的函数,我想在页面加载时调用它

componentDidMount() {
  this.getDeductionInfosList();

this.state=  this.createAppState({
        group: [{ field: "DeductionTypeTitle"   }], true)
  }
 
 getDeductionInfosList(data) {
    GetRestrictionListService.getDeductionInfos( data,this.successGetDeductionInfos);
  }
  successGetDeductionInfos = (response) => {
    if (response.Result) {
      this.setState({
        items: response.Result,
      });
    
    }
  };
createAppState(dataState, collapseAll) {
  const dataResult = process( this.state.items, dataState);
  console.log(this.state.items)
  if (collapseAll) {
    dataResult.data.forEach(dataItem => dataItem.expanded = false);

  }
  this.setState({
    dataResult: dataResult,
      dataState: dataState 
  }) ;


}

但是当我在 componentDidMount Returns 项目空数组中使用它时如何先从 Api 获取数据然后调用 this.createAppState 函数

您必须将函数转换为 async 并使用 await 作为响应。

async function getDeductionInfosList(data){ await GetRestrictionListService.getDeductionInfos(data, this.successGetDeductionInfos);}

您的代码中存在一些问题

  1. setState 可能是异步的,这意味着调用 setState 后状态不会立即更新。 React 文档中清楚地提到了它:https://reactjs.org/docs/state-and-lifecycle.html#state-updates-may-be-asynchronous
  2. 永远不要直接修改 componentDidMount 里面的状态 这里也提到了:https://reactjs.org/docs/state-and-lifecycle.html#do-not-modify-state-directly 所以我建议修改代码如下


    componentDidMount() {
      this.getDeductionInfosList(data, function(response){
        this.createAppState({
            group: [{ field: "DeductionTypeTitle" }]}, response.Result, true)
      });
    }
    createAppState(dataState, items collapseAll) {
      const dataResult = process( items, dataState);
      if (collapseAll) {
        dataResult.data.forEach(dataItem => dataItem.expanded = false);
      }
      this.setState({
        dataResult: dataResult,
        dataState: dataState 
      });
    }