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. 数据湖-Apache Hudi

    Hudi特性 数据湖处理非结构化数据.日志数据.结构化数据 支持较快upsert/delete, 可插入索引 Table Schema 小文件管理Compaction ACID语义保证,多版本保证 并 ...

  2. 《CSP.OI吟》

    吟 CSP·OI 这个LCT,我听得很懵逼 在 Splay 里面,好像有重链 不用线段树,Splay 来维护 树的形态有改变,不只是那一条边 所以要把整棵树,重新剖一遍 什么重链 ~ 什么轻边 ~ 什 ...

  3. maven pom文件的 name 标签 和 url标签到底是什么作用

  4. Linux内核poll/select机制简析

    0 I/O多路复用机制 I/O多路复用 (I/O multiplexing),提供了同时监测若干个文件描述符是否可以执行IO操作的能力. select/poll/epoll 函数都提供了这样的机制,能 ...

  5. 深入理解java虚拟机,GC参考手册

    深入理解java虚拟机 一.<深入理解Java虚拟机> 1.第2章 Java内存区域与内存溢出异常 2.第3章 垃圾收集器与内存分配策略 3.第4章 虚拟机性能监控与故障处理工具 4.第5 ...

  6. toggle() 隐藏和收缩

    <!DOCTYPE html><html><head><script src="/jquery/jquery-1.11.1.min.js" ...

  7. java切割~~百万 十万 万 千 百 十 个 角 分

    /** * @param value * @return */ @SuppressWarnings("unused") public static void convertLoan ...

  8. js文字颜色闪烁

    <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/ ...

  9. docker学习二

    B站视频地址 3.docker的基本操作 3.1 安装docker 1.下载关于Docker的依赖环境 想安装Docker,需要先将依赖的环境全部下载下来,就像Maven依赖JDK一样 yum -y ...

  10. [源码分析] Dynomite 分布式存储引擎 之 DynoJedisClient(1)

    [源码分析] Dynomite 分布式存储引擎 之 DynoJedisClient(1) 目录 [源码分析] Dynomite 分布式存储引擎 之 DynoJedisClient(1) 0x00 摘要 ...