简体   繁体   English

如何使用 UseEffect 在加载功能组件时运行多个查询并在渲染方法中获取结果?

[英]How can I run multiple queries on load of functional component using UseEffect and get result in render method?

I have the following functional component where, on load of the component, it needs to loop through an array and run some async queries to populdate a new array I want to display in render method.我有以下功能组件,在加载组件时,它需要遍历一个数组并运行一些异步查询来填充一个我想在渲染方法中显示的新数组。

     import React, { useEffect, useState, useContext } from 'react';
     import { AccountContext } from '../../../../providers/AccountProvider';
     import { GetRelationTableCount } from '../../../../api/GetData';
     import { getTableAPI } from '../../../../api/tables';

  const RelatedRecordsPanel = (props) => {
  const { userTokenResult } = useContext(AccountContext);
  const { dataItem } = props;

  const [relatedTableItems, setRelatedTableItems] = useState([]);

   useEffect(() => {
      const tempArray = [];
      const schema = `schema_${userTokenResult.zoneId}`;
      const fetchData = async () => {

     return Promise.all(
        dataItem.tableinfo.columns
        .filter((el) => el.uitype === 1)
        .map(async (itm) => {
          const tblinfo = await getTableAPI(itm.source.lookuptableid);
          const tblCount = await GetRelationTableCount(
           dataItem.tableid,
          itm.source.jointable,
          schema,
        );

        const TableIconInfo = { name: tblinfo.name, icon: tblinfo.icon, count: tblCount };
        tempArray.push(TableIconInfo);

      })

  );
};
 fetchData();
setRelatedTableItems(tempArray)
 }, []);

  return (
     <div>
       {relatedTableItems.length > 0 ? <div>{relatedTableItems.name}</div> : null}
  </div>
  );
  };

In the above code, the queries run correctly and if I do a console.log in the loop, I can see if fetches the data fine, however, the array is always [] and no data renders.在上面的代码中,查询运行正确,如果我在循环中执行 console.log,我可以查看是否可以正常获取数据,但是,数组始终是 [] 并且没有数据呈现。 How do I write this async code such that it completes the queries to populate the array, so that I can render properly?如何编写此异步代码以完成查询以填充数组,以便我可以正确呈现?

Thx!谢谢!

You aren't using the return value of the Promise.all and since all your APIs are async, the tempArray is not populated by the time you want to set it into state您没有使用 Promise.all 的返回值,并且由于您的所有 API 都是异步的,因此在您要将其设置为 state 时不会填充 tempArray

You can update it like below by waiting on the Promise.all result and then using the response您可以通过等待 Promise.all 结果然后使用响应来更新它,如下所示

useEffect(() => {
      const schema = `schema_${userTokenResult.zoneId}`;
      const fetchData = async () => {

     return Promise.all(
        dataItem.tableinfo.columns
        .filter((el) => el.uitype === 1)
        .map(async (itm) => {
          const tblinfo = await getTableAPI(itm.source.lookuptableid);
          const tblCount = await GetRelationTableCount(
           dataItem.tableid,
          itm.source.jointable,
          schema,
        );

        const TableIconInfo = { name: tblinfo.name, icon: tblinfo.icon, count: tblCount };
        return TableIconInfo;

      })

  );
};
 fetchData().then((res) => {
     setRelatedTableItems(res);
 });

 }, []);

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

相关问题 如何有条件地渲染功能组件中的项目? - How can conditionally render items in functional component? 想将 class 组件转换为功能组件它有两个渲染方法所以我很困惑如何转换它 - want to convert class component into functional component it has two render method so i am confused how to convert it 如何使用快照在 useEffect 内部使用异步回调测试功能组件 - How to test functional component with async callback inside useEffect using snapshots 如何在功能组件中使用 ref 访问组件的方法 - How can I access methods of a component using ref in functional component 如何正确获取此组件以进行渲染? - How can I correctly get this component to render? 在反应功能组件中使用 useEffect 时出错 - Error using useEffect in react functional component 在功能组件中使用“useEffect”时出错 - Getting error when using “useEffect” in functional component 如何使用反应功能组件添加或删除 class - How can I add or remove class using react functional component 如何防止功能组件中的重新渲染错误? - How can I prevent a re-render error in my functional component? 在功能组件内的功能组件中调用 useEffect 会导致此消息:Rendered more hooks than the previous render - Calling useEffect in a functional component within a functional component causes this message: Rendered more hooks than during the previous render
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM