简体   繁体   English

如何在 reactjs 中同时渲染不同的 api 组件?

[英]How to render different api components at same time in reactjs?

i am having a container where i am rendering 4 components, each components hitting the api.我有一个容器,我在其中渲染 4 个组件,每个组件都命中 api。 Api response is coming diffrent timing for this 4 components. Api 对这 4 个组件的响应时间不同。 Because of that one component is loaded fastly and another one taking time.因为一个组件加载速度很快,而另一个组件需要时间。 This make the ui to not look good.这使用户界面看起来不太好。

Is there any other way to load different components at same time in react.有没有其他方法可以在反应中同时加载不同的组件。

在此处输入图像描述

you can use Suspense like below:你可以像下面这样使用悬念:

import React, { Suspense } from "react";
import ReactDOM from "react-dom";

import "./styles.css";
import { fetchProfileData } from "./fakeApi";

const resource = fetchProfileData();

function ProfilePage() {
  return (
    <Suspense
      fallback={<h1>Loading profile...</h1>}
    >
      <ProfileDetails />
      <Suspense
        fallback={<h1>Loading posts...</h1>}
      >
        <ProfileTimeline />
      </Suspense>
    </Suspense>
  );
}

function ProfileDetails() {
  // Try to read user info, although it might not have loaded yet
  const user = resource.user.read();
  return <h1>{user.name}</h1>;
}

function ProfileTimeline() {
  // Try to read posts, although they might not have loaded yet
  const posts = resource.posts.read();
  return (
    <ul>
      {posts.map(post => (
        <li key={post.id}>{post.text}</li>
      ))}
    </ul>
  );
}

const rootElement = document.getElementById(
  "root"
);
ReactDOM.createRoot(rootElement).render(
  <ProfilePage />
);

More detail更多详情

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

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