繁体   English   中英

React Hooks - 根据循环中的多个异步调用设置 state

[英]React Hooks - Set state based on multiple async calls in loop

我的以下效果是尝试完成以下操作:

  1. 我需要为工作、发布和销售项目发出 3 个并发 XHR 请求。
  2. 当数据返回时,我需要将记录分类为打开、关闭和“其他”arrays,然后将 append 分类为“running_total”数组。
  3. 一旦所有 XHR 请求都完成并排序,我想将 running_total 数组设置为 state。

不幸的是,我下面的代码似乎不尊重 async / await 并且一旦效果完成运行,我最终得到一个空数组。 有什么想法我可能做错了吗?

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 function 看起来像:

async function get_data (endpoint, params) {
    if (params === null) {
        return await axios.get(endpoint)
    } else{
        return await axios.get(endpoint, {params: params});
    }
};

您可能还想阅读此博客,在 useEffect 上使用异步

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

希望这可以帮助

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM