React Hooks-基于循环中的多个异步调用设置状态

问题描述 投票:0回答:1

我下面的效果是试图完成以下任务:

  1. 我需要同时发出3个XHR职位,职位和销售项目的请求。
  2. 当数据返回时,我需要将记录分为打开,关闭和“最热”数组,然后将它们追加到“ running_total”数组中。
  3. 一旦所有XHR请求都已完成并排序,我想将running_total数组设置为state。

[不幸的是,我的以下代码似乎不尊重异步/等待,一旦效果运行完毕,我最终得到一个空数组。有什么想法我可能做错了吗?

useEffect(() => {
    const types = ["jobs", "postings", "sale_items"];

    async function getEntityReferencesAsync() {
      let running_total = [];
      types.forEach(
        function(type) {
          let open = [];
          let closed = [];
          let therest = [];

          const request = await get_data(
            `https://myapi.com.com/${type}/${props.id}`
          );

          response.then(
            function(result) {
              const result_array = result.data.records;
              result_array.forEach(
                function(item) {
                  item["type"] = type;
                  if (item.status === "open") {
                    open.push(item);
                  } else if (item.status === "closed") {
                    closed.push(item);
                  } else {
                    therest.push(item);
                  }
                }.bind(this)
              );

              running_total = [
                ...running_total,
                ...open,
                ...closed,
                ...therest
              ];
            }.bind(this)
          );
        }.bind(this)
      );
      return running_total;
    }

    async function getSortedData() {
      const sorted_array = await getEntityReferencesAsync();
      setEntityReferencesData(sorted_array);
    }

    getSortedData();
  }, [props.id]);

仅供参考,我的get_data函数看起来像:

async function get_data (endpoint, params) {
    if (params === null) {
        return await axios.get(endpoint)
    } else{
        return await axios.get(endpoint, {params: params});
    }
};
reactjs asynchronous async-await react-hooks
1个回答
0
投票

您可能还希望阅读此博客,在useEffect上使用异步方法

https://www.robinwieruch.de/react-hooks-fetch-data

希望这会有所帮助

© www.soinside.com 2019 - 2024. All rights reserved.