简体   繁体   English

React:在渲染子组件之前等待 API 获取和 LocalStorage 设置

[英]React: Await for API fetch and LocalStorage set before render children components

I have the following app entry component:我有以下应用程序入口组件:

  React.useEffect(() => {
    const fetchData = async () => {
      try {
        const libraries: unknown[] = await sendRequest('/libraries');
        const softwareComponents: unknown[] = await sendRequest('/softwareComponents');

        localStorage.setItem('libraries', JSON.stringify(arraySetup(libraries, 'libraries')));
        localStorage.setItem('softwareComponents', JSON.stringify(arraySetup(softwareComponents, 'software-components')));
      } catch (err) {
        console.error(err);
      }
    };
    isAuthenticated() && fetchData();
  }, []);

I am fetching Arrays from two endpoints and then set the result in the Local Storage, so I can read from it in other components.我从两个端点获取 Arrays,然后将结果设置在本地存储中,这样我就可以在其他组件中读取它。

A child component is using the data like this:子组件正在使用这样的数据:

  const [data, setData] = React.useState<Array<any>>([]);

  React.useEffect(() => {
    const libraries = getLocalStorageItem('libraries');
    const softwareComponents = getLocalStorageItem('softwareComponents');
    const condition = libraries && softwareComponents;

    if (condition) {
      setData([...libraries, ...softwareComponents]);
    }
  }, []);

  const getDataLength = (category: string) => {
    return (data || []).filter((item: any) => item.category === category).length;
  };

  return (
    <React.Fragment>
      <OwcGrid item xs={12} s={4}>

        <LibrariesCard numberOfElements={getDataLength('libraries')} /> // rendering here the length of the localStorage item.

      </OwcGrid>

The following bug now exists:现在存在以下错误:

Opening the app for the first time, the API is called and the localstorage is set.第一次打开应用程序,调用 API 并设置 localstorage。

But the child components that are using localStorage are rendered at the same time, so if (condition) setData([...libraries, ...softwareComponents]);但是使用 localStorage 的子组件是同时渲染的,所以if (condition) setData([...libraries, ...softwareComponents]); is never met and the numberOfElements prop is always empty at the first time.永远不会遇到,并且numberOfElements道具在第一次总是空的。

Only at the second refresh, localStorage is in place and I can count the elements out from it and render it.只有在第二次刷新时,localStorage 就位,我可以从中计算出元素并渲染它。

Can somebody give me a hint to wait for localStorage.setItem in the App.layout or if I can wait and check in the child components as long as the storage is set and then render again?有人可以提示我在 App.layout 中等待localStorage.setItem吗,或者我是否可以等待并在设置了存储后检查子组件然后再次渲染?

Do you have to use local storage?你必须使用本地存储吗? You could solve your problem by using context api, where you can store all required values and use them in any component that you need to.您可以通过使用上下文 api 来解决您的问题,您可以在其中存储所有必需的值并在您需要的任何组件中使用它们。 If you have to use local storage, you can manage it from context.如果您必须使用本地存储,则可以从上下文中对其进行管理。

Please checkout documentation for context: https://reactjs.org/docs/context.html请查看上下文文档: https://reactjs.org/docs/context.html

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

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