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. 线上一次大量 CLOSE_WAIT 复盘

    https://mp.weixin.qq.com/s/PfM3hEsDa3CMLbbKqis-og 线上一次大量 CLOSE_WAIT 复盘 原创 ms2008 poslua 2019-07-05 最 ...

  2. Nagle's algorithm 封包 网络游戏协议封包需注意点 封包挂

    w41字节的数据包只有1字节的可用信息.以减少数据包发送量来提高TCP/IP网络性能. https://en.wikipedia.org/wiki/Nagle's_algorithm https:// ...

  3. Pulsar Pub/Sub Messaging

    The Apache Software Foundation Announces Apache Pulsar as a Top-Level Project : The Apache Software ...

  4. BIO,NIO,AIO 总结

    BIO,NIO,AIO 总结 Java 中的 BIO.NIO和 AIO 理解为是 Java 语言对操作系统的各种 IO 模型的封装.程序员在使用这些 API 的时候,不需要关心操作系统层面的知识,也不 ...

  5. loj1011愤怒的牛

    题目描述 原题来自:USACO 2005 Feb. Gold 农夫约翰建造了一座有 n 间牛舍的小屋,牛舍排在一条直线上,第 i 间牛舍在 x_i 的位置,但是约翰的 m 头牛对小屋很不满意,因此经常 ...

  6. CQOI 2006 简单题

    CQOI 2006 简单题 有一个 n 个元素的数组,每个元素初始均为 0.有 m 条指令,要么让其中一段连续序列数字反转--0 变 1,1 变 0(操作 11),要么询问某个元素的值(操作 2). ...

  7. 二:整合Spring Security

    整合Spring Security 1.项目创建 2.初次体验 3.用户名配置 3.1 配置文件配置用户名/密码 3.2 Java 配置用户名/密码 4.登录配置 5.忽略拦截 江南一点雨:Sprin ...

  8. GeoJson的生成与解析,JSON解析,Java读写geojson,geotools读取shp文件,Geotools中Geometry对象与GeoJson的相互转换

    GeoJson的生成与解析 一.wkt格式的geometry转成json格式 二.json格式转wkt格式 三.json格式的数据进行解析 四.Java读写geojson 五.geotools读取sh ...

  9. MapReduce编程练习(三),按要求不同文件名输出结果

    问题:按要求文件名输出结果,比如这里我要求对一个输入文件中的WARN,INFO,ERROR,的信息项进行分析,并分别输入到对应的以WARN,INFO.ERROR和OTHER开头的结果文件中,其中结果文 ...

  10. ElasticSearch 安装与运行

    公号:码农充电站pro 主页:https://codeshellme.github.io 本节来介绍 ES 的安装. 1,下载 ES ES 是基于 Java 语言开发的,因此,要安装 ES,首先需要有 ...