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>
);
}

这就提出了一个问题,即在渲染下一个屏幕之前我们如何知道要获取什么?

https://reactjs.org/blog/2019/11/06/building-great-user-experiences-with-concurrent-mode-and-suspense.html

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

  1. 时间分片

xgqfrms 2012-2020

www.cnblogs.com 发布文章使用:只允许注册用户才可以访问!


Suspense for Data Fetching的更多相关文章

  1. [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 ...

  2. [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 ...

  3. 深度理解 React Suspense(附源码解析)

    本文介绍与 Suspense 在三种情景下使用方法,并结合源码进行相应解析.欢迎关注个人博客. Code Spliting 在 16.6 版本之前,code-spliting 通常是由第三方库来完成的 ...

  4. [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 ...

  5. [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 ...

  6. React 特性剪辑(版本 16.0 ~ 16.9)

    Before you're going to hate it, then you're going to love it. Concurrent Render(贯穿 16) 在 18年的 JSConf ...

  7. React + Redux 入坑指南

    Redux 原理 1. 单一数据源 all states ==>Store 随着组件的复杂度上升(包括交互逻辑和业务逻辑),数据来源逐渐混乱,导致组件内部数据调用十分复杂,会产生数据冗余或者混用 ...

  8. Java性能提示(全)

    http://www.onjava.com/pub/a/onjava/2001/05/30/optimization.htmlComparing the performance of LinkedLi ...

  9. A beginner’s guide to Cache synchronization strategies--转载

    原文地址:http://vladmihalcea.com/2015/04/20/a-beginners-guide-to-cache-synchronization-strategies/ Intro ...

随机推荐

  1. 关于BI测试

    BI测试: BI是从数据接入.数据准备.数据分析.数据可视化到数bai据分发应用的一系列过程,目的是为了辅助企业高效决策.而报表虽然最终也实现了数据可视化,但是对于数据分析的维度.深度.颗粒度.实时性 ...

  2. 网络Devops探索与实践 流程管理分析师

    https://mp.weixin.qq.com/s/OKLiDi78uB8ZkPG2kUVxvA 网络Devops探索与实践 王镇 鹅厂网事 2020-09-23  9月16日举办的2020 ODC ...

  3. 深入理解 MySQL 索引底层原理

    https://mp.weixin.qq.com/s/qHJiTjpvDikFcdl9SRL97Q

  4. Vue中双向数据绑定是如何实现的?

    vue 双向数据绑定是通过 数据劫持 结合 发布订阅模式的方式来实现的, 也就是说数据和视图同步,数据发生变化,视图跟着变化,视图变化,数据也随之发生改变:核心:关于VUE双向数据绑定,其核心是 Ob ...

  5. 系列trick - 建图

    对偶图 主体思想:平面图的割,等价于对偶图的路 例题:[BeiJing2006]狼抓兔子 网上有114514篇题解,这里不赘述 点变边 主体思想:点带点权,而要在点上实现一些在边上的问题,比如最小割点 ...

  6. Spring Boot:添加导出Excel表格功能

    1.添加POI依赖 2.创建EXCEL实体类 3.创建表格工具类 4.创建ExcelConstant 5.创建ExcelController 1.添加POI依赖 <dependency> ...

  7. Spring Boot的进阶和高级

    一.Repository接口 二.Repository子接口 三.@Query注解 四.更新及删除操作整合事物 五.CrudRepository接口 六.PagingAndSortingReposit ...

  8. Hyperbase常用SQL

    1.创建表 1.1 建HBase内表 CREATE TABLE hbase_inner_table(   key1 string,   bi bigint,   dc decimal(10,2),   ...

  9. 2019 Multi-University Training Contest 2 Harmonious Army(最小割)

    题意:给你n个点 每个点都有两种选择 成为战士或者法师 现在给你m个关系 对应这两个人的对应关系的权值A,B,C 思路:按照下面的思路建图跑最小割(要注意权值要乘2 可能存在不整除的情况) #incl ...

  10. 2019HDU多校 Round3

    09 K Subsequence #include <bits/stdc++.h> using namespace std; typedef long long ll; const int ...