【问题标题】:react Suspense is not working and i don't know why反应悬念不起作用,我不知道为什么
【发布时间】:2021-10-26 23:16:51
【问题描述】:

我得到了一个项目来找出以下代码行不起作用的原因。 以下代码实现了 React Suspense API, 但这样做不正确。这些组件如何利用 Suspense 和并发模式存在 3 个核心问题 这是我不熟悉的东西,即使在阅读了文档后我仍然无法修复它

import { Suspense, useState, useEffect } from 'react';

const SuspensefulUserProfile = ({ userId }) => {
  const [data, setData] = useState({});
  useEffect(() => {
    fetchUserProfile(userId).then((profile) => setData(profile));
  }, [userId, setData])
  return (
    <Suspense>
      <UserProfile data={data} />
    </Suspense>
  );
};
const UserProfile = ({ data }) => {
  return (
    <>
      <h1>{data.name}</h1>
      <h2>{data.email}</h2>
    </>
  );
};
const UserProfileList = () => (
  <>
    <SuspensefulUserProfile userId={1} />
    <SuspensefulUserProfile userId={2} />
    <SuspensefulUserProfile userId={3} />
  </>
);

【问题讨论】:

    标签: javascript reactjs components rest react-suspense


    【解决方案1】:

    要使 Suspense 具有任何值,您需要异步加载组件。这通常转化为动态导入。

    export default const UserProfile = ({ data }) => {
      return (
        <>
          <h1>{data.name}</h1>
          <h2>{data.email}</h2>
        </>
      );
    };
    

    只有在需要 React 的惰性时才导入 UserProfile:

    const UserProfile = React.lazy(() => import('./UserProfile'))
    

    并使用它:

    <Suspense fallback={'Loading...'}>
      <UserProfile data={data} />
    </Suspense>
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-12-15
      • 2019-01-12
      • 1970-01-01
      • 2020-09-16
      • 1970-01-01
      • 2016-08-25
      • 2013-11-27
      • 1970-01-01
      相关资源
      最近更新 更多