Suspense for Data Fetching
Suspense for Data Fetching
Experimental
https://reactjs.org/docs/concurrent-mode-suspense.html
React 16.6
const ProfilePage = React.lazy(() => import('./ProfilePage'));
// Lazy-loaded
// Show a spinner while the profile is loading
<Suspense fallback={<Spinner />}>
<ProfilePage />
</Suspense>
Fetch-on-Render
bad
// In a function component:
useEffect(() => {
fetchSomething();
}, []);
// Or, in a class component:
componentDidMount() {
fetchSomething();
}
function ProfilePage() {
const [user, setUser] = useState(null);
useEffect(() => {
fetchUser().then(u => setUser(u));
}, []);
if (user === null) {
return <p>Loading profile...</p>;
}
return (
<>
<h1>{user.name}</h1>
<ProfileTimeline />
</>
);
}
function ProfileTimeline() {
const [posts, setPosts] = useState(null);
useEffect(() => {
fetchPosts().then(p => setPosts(p));
}, []);
if (posts === null) {
return <h2>Loading posts...</h2>;
}
return (
<ul>
{posts.map(post => (
<li key={post.id}>{post.text}</li>
))}
</ul>
);
}
Fetch-Then-Render
Promise.all & react hooks
better
function fetchProfileData() {
return Promise.all([
fetchUser(),
fetchPosts()
]).then(([user, posts]) => {
return {user, posts};
})
}
// Kick off fetching as early as possible
const promise = fetchProfileData();
function ProfilePage() {
const [user, setUser] = useState(null);
const [posts, setPosts] = useState(null);
useEffect(() => {
promise.then(data => {
setUser(data.user);
setPosts(data.posts);
});
}, []);
if (user === null) {
return <p>Loading profile...</p>;
}
return (
<>
<h1>{user.name}</h1>
<ProfileTimeline posts={posts} />
</>
);
}
// The child doesn't trigger fetching anymore
function ProfileTimeline({ posts }) {
if (posts === null) {
return <h2>Loading posts...</h2>;
}
return (
<ul>
{posts.map(post => (
<li key={post.id}>{post.text}</li>
))}
</ul>
);
}
Render-as-You-Fetch / 按需渲染
Suspense
good
// This is not a Promise. It's a special object from our Suspense integration.
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>
);
}
这就提出了一个问题,即在渲染下一个屏幕之前我们如何知道要获取什么?
Errors & ErrorBoundary
getDerivedStateFromError
// Error boundaries currently have to be classes.
class ErrorBoundary extends React.Component {
state = { hasError: false, error: null };
static getDerivedStateFromError(error) {
return {
hasError: true,
error
};
}
render() {
if (this.state.hasError) {
return this.props.fallback;
}
return this.props.children;
}
}
function ProfilePage() {
return (
<Suspense fallback={<h1>Loading profile...</h1>}>
<ProfileDetails />
<ErrorBoundary fallback={<h2>Could not fetch posts.</h2>}>
<Suspense fallback={<h1>Loading posts...</h1>}>
<ProfileTimeline />
</Suspense>
</ErrorBoundary>
</Suspense>
);
}
https://aweary.dev/fault-tolerance-react/
https://codesandbox.io/s/infallible-feather-xjtbu
relay
suspense integration
https://relay.dev/docs/en/experimental/step-by-step
https://relay.dev/docs/en/experimental/api-reference#usepreloadedquery
fetch data with React Hooks
https://www.robinwieruch.de/react-hooks-fetch-data
Concurrent Mode
https://reactjs.org/docs/concurrent-mode-intro.html
react fiber
- 时间分片
xgqfrms 2012-2020
www.cnblogs.com 发布文章使用:只允许注册用户才可以访问!
Suspense for Data Fetching的更多相关文章
- [NgRx] NgRx Data Fetching Solution - How to Load Data Only If Needed
We have a reoslver, which everytime we want visit '/courses' route, it will be triggered, then api w ...
- [React] Fetch Data with React Suspense
Let's get started with the simplest version of data fetching with React Suspense. It may feel a litt ...
- 深度理解 React Suspense(附源码解析)
本文介绍与 Suspense 在三种情景下使用方法,并结合源码进行相应解析.欢迎关注个人博客. Code Spliting 在 16.6 版本之前,code-spliting 通常是由第三方库来完成的 ...
- [React] Write a generic React Suspense Resource factory
Using Suspense within our component isn't exactly ergonomic. Let's put all that logic into a reusabl ...
- [MST] Loading Data from the Server using lifecycle hook
Let's stop hardcoding our initial state and fetch it from the server instead. In this lesson you wil ...
- React 特性剪辑(版本 16.0 ~ 16.9)
Before you're going to hate it, then you're going to love it. Concurrent Render(贯穿 16) 在 18年的 JSConf ...
- React + Redux 入坑指南
Redux 原理 1. 单一数据源 all states ==>Store 随着组件的复杂度上升(包括交互逻辑和业务逻辑),数据来源逐渐混乱,导致组件内部数据调用十分复杂,会产生数据冗余或者混用 ...
- Java性能提示(全)
http://www.onjava.com/pub/a/onjava/2001/05/30/optimization.htmlComparing the performance of LinkedLi ...
- A beginner’s guide to Cache synchronization strategies--转载
原文地址:http://vladmihalcea.com/2015/04/20/a-beginners-guide-to-cache-synchronization-strategies/ Intro ...
随机推荐
- Model(metaclass=ModelBase)
Python装饰器.metaclass.abc模块学习笔记 - 王智愚 - 博客园 https://www.cnblogs.com/Security-Darren/p/4094959.html dja ...
- ensure that both new and old access_token values are available within five minutes, so that third-party services are smoothly transitioned.
WeChat public doc https://developers.weixin.qq.com/doc/offiaccount/en/Basic_Information/Get_access_t ...
- 004_C++常见错误类型总结(一)之最后几行错误
1.介绍 经常进行代码测试和静态代码分析的同学,应该会遇到这样的一个问题,就是一个程序段的最后几行,或者一个源文件末尾会出现错误.本文,结合专业的静态代码分析软件PSV-Studio提供错误类型代码库 ...
- lodash的debounce函数的使用
最新,在react新项目的开发中使用到了lodash类库的debounce方法,就随手梳理了一下此方法的方便之处 未使用debounce之前 如果不考虑使用debounce,那么在用户连续点击的情况之 ...
- Web漏洞扫描-AWVS
Web漏洞扫描-AWVS 一.AWVS概述 二.功能以及特点 三.AWVS界面 四.AWVS使用 相关优质博文: CSDN:帽子不够白:WEB渗透测试之三大漏扫神器 一.AWVS概述 Acunetix ...
- Spark获取DataFrame中列的方式--col,$,column,apply
Spark获取DataFrame中列的方式--col,$,column,apply 1.官方说明 2.使用时涉及到的的包 3.Demo 原文作者:大葱拌豆腐 原文地址:Spark获取DataFrame ...
- Linux内存运维操作及常用命令
Linux内存运维操作及常用命令 1.问题诊断 1.1 什么是 Linux 服务器 Load Average? 1.2如何查看 Linux 服务器负载? 1.3服务器负载高怎么办? 1.4如何查看服务 ...
- Ajax原理,技术封装与完整示例代码
在做项目和学习的时候,经常用到Ajax的相关技术,但是这方面的技术总是运用的不是十分好,就寻找相关博客来学习加深Ajax技术相关. 一.Ajax简介 二.同步.异步传输区别 2.1 异步传输 2.2 ...
- centos7系统忘记root密码
第一步:开启服务器,在如下界面键入"e"进入编辑 第二步:找到以linux16开头的一行,在本行行尾键入"rd.break" 第三步:输入完成后,按" ...
- 并发队列:ArrayBlockingQueue实际运用场景和原理
ArrayBlockingQueue实际应用场景 之前在某公司做过一款情绪识别的系统,这套系统通过调用摄像头接口采集人脸信息,将采集的人脸信息做人脸识别和情绪分析,最终经过一定的算法将个人情绪数据转化 ...