简体   繁体   English

React Suspense 不起作用,我不知道为什么

[英]react Suspense is not working and i don't know why

I was given a project to find out why the below lines of code isn't working.我得到了一个项目来找出为什么下面的代码行不起作用。 The following code implement the React Suspense API, but does so incorrectly.以下代码实现了 React Suspense API,但这样做不正确。 There are 3 core issues with how these components utilize Suspense and concurrent mode which is something I'm not Familiar with and even after reading the documentation I still can't fix it这些组件如何利用 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} />
  </>
);

For Suspense to have any value, you want to load a component asynchronously.为了让 Suspense 具有任何价值,您需要异步加载组件。 That usually translate on doing dynamic imports.这通常转化为动态导入。

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

You then import UserProfile only when's needed with React's lazy:然后,仅在需要 React 的惰性时才导入 UserProfile:

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

And use it:并使用它:

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

You will have to pass fallback.您将不得不通过后备。 Without fallback it wont work.没有后备它不会工作。

<Suspense fallback={<div>Loading</div>}>
or
<Suspense fallback={<></>}>

What worked for me is lazy loading, from Federkun's example:对我有用的是延迟加载,来自 Federkun 的示例:

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

One note is that it only works if the eslint parser is set to:需要注意的是,它仅在 eslint 解析器设置为:

"parser": "babel-eslint"

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

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