我正在努力寻找使用 的问题悬疑和 react 钩子(Hook) .
有几个关键问题使用下面的 React 代码。
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} />
</>
};
让我知道它们是什么。我发现了两个关键问题。
setdata
在 useEffect
依赖数组 suspense
fallback
Prop 。 我认为仍然存在一个关键问题。
一件奇怪的事情是为什么
userId
需要包含在依赖数组中。
最佳答案
你误用了Suspense
到它的核心,至少在数据获取的悬念可用之前。
Suspense 目前仅适用于 React.lazy
组件,而不是应用程序的任意“加载”状态。例如,React 应该如何计算出你的 data
正在加载?Suspense
的唯一用途是允许在 React 加载惰性组件时显示一些后备。对于其他类型的延迟加载应用程序数据,您可以实现自己的回退,如:
const SuspensefulUserProfile = ({ userId }) => {
const [data, setData] = useState();
useEffect(() => {
fetchUserProfile(userId).then(setData);
}, [userId])
return data ? <UserProfile data={data} /> : 'Loading...';
};
关于javascript - 了解 Suspense 和 React Hooks,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64251098/