【问题标题】:How to get data from Api first and then call the my function?如何先从 Api 获取数据,然后调用 my 函数?
【发布时间】:2020-09-05 12:23:39
【问题描述】:

我有一个在剑道网格中分组的功能,我想在页面加载时调用它

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中使用时返回item空数组如何先从Api获取数据然后调用this.createAppState函数

【问题讨论】:

    标签: javascript reactjs kendo-grid


    【解决方案1】:

    您的代码中存在一些问题

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

    【讨论】:

      【解决方案2】:

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

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

      【讨论】:

      • 我按照你说的方式试过了,但是 createAppState 函数中的项仍然是空数组
      • 查看编辑后的答案,我第一次错了。这次不答应我是对的xD
      • 您也可以尝试使整个函数异步并等待第二个函数:async function componentDidMount(){....await getDeductionInfoList(data){...。发生这种情况是因为响应晚于函数的执行。所以执行必须等待响应。使用 await,你这样做,它不会走得更远,直到响应到来。
      • 感谢您的回答
      猜你喜欢
      • 2020-10-20
      • 1970-01-01
      • 2017-11-02
      • 2020-09-26
      • 2021-07-14
      • 2021-03-13
      • 1970-01-01
      • 1970-01-01
      • 2020-07-28
      相关资源
      最近更新 更多