【发布时间】:2021-01-22 19:50:08
【问题描述】:
我正在努力寻找使用 Suspense 和 React hooks 的问题。
下面的 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} />
</>
};
让我知道它们是什么。
我发现了两个关键问题。
- 在
useEffect依赖数组中滥用setdata - 没有提供
suspensefallback道具。
我认为还有一个关键问题。
一个奇怪的事情是为什么userId 需要包含在依赖数组中。
【问题讨论】:
-
我发现悬念是experimental 的功能!
-
这是一道作业题吗?
-
@Mordechai 这是一个求职面试问题。我发现了两个关键问题。但他们说还有一个。
-
仅供参考,
setData是否在依赖项列表中没有区别。它已经被useState()记住了,所以 React 不需要在组件实例的每个渲染上都对其进行引用检查。但是,允许对其进行引用检查不会影响组件的行为。所以你第一个发现的关键“问题”并不是真正的问题,它只是一个冗余。
标签: javascript reactjs typescript react-hooks react-suspense