React 之 Suspense提出的背景及使用详解

Suspense 提出的背景

假设我们现在有如下一个应用:

  1. const Articles = () => {
  2.      const [articles, setArticles] = useState(null)
  3.      useEffect(() => {
  4.      getArticles().then((a) => setArticles(a))
  5.      }, [])
  6.      if (articles === null) {
  7.      return <p>Loading articles…</p>
  8.      }
  9.      return (
  10.      <ul>
  11.          {articles.map((article) => (
  12.          <li key={article.id}>
  13.              <h4>{article.title}</h4>
  14.              <p>{article.abstract}</p>
  15.          </li>
  16.          ))}
  17.      </ul>
  18.      )
  19. }
  20. export default function Profile() {
  21.      const [user, setUser] = useState(null)
  22.      useEffect(() => {
  23.      getUser().then((u) => setUser(u))
  24.      }, [])
  25.      if (user === null) {
  26.      return <p>Loading user…</p>
  27.      }
  28.      return (
  29.      <>
  30.          <h3>{user.name}</h3>
  31.          <Articles articles={articles} />
  32.      </>
  33.      )
  34. }

该应用是一个用户的个人主页,包含用户的基本信息(例子中只有名字)以及用户的文章列表,并且规定了必须等待用户获取成功后才能渲染其基本信息以及文章列表。 该应用看似简单,但却存在着以下几个问题:

  • “Waterfalls”,意思是文章列表必须要等到用户请求成功以后才能开始渲染,从而对于文章列表的请求也会被用户阻塞,但其实对于文章的请求是可以同用户并行的。
  • “fetch-on-render”,无论是 Profile 还是 Articles 组件,都是需要等到渲染一次后才能发出请求。

对于第一个问题,我们可以通过修改代码来优化:

  1. const Articles = ({articles}) => {
  2.      if (articles === null) {
  3.      return <p>Loading articles…</p>
  4.      }
  5.      return (
  6.      <ul>
  7.          {articles.map((article) => (
  8.          <li key={article.id}>
  9.              <h4>{article.title}</h4>
  10.              <p>{article.abstract}</p>
  11.          </li>
  12.          ))}
  13.      </ul>
  14.      )
  15. }
  16. export default function Profile() {
  17.      const [user, setUser] = useState(null)
  18.      const [articles, setArticles] = useState(null)
  19.      useEffect(() => {
  20.      getUser().then((u) => setUser(u))
  21.      getArticles().then((a) => setArticles(a))
  22.      }, [])
  23.      if (user === null) {
  24.      return <p>Loading user…</p>
  25.      }
  26.      return (
  27.      <>
  28.          <h3>{user.name}</h3>
  29.          <Articles articles={articles} />
  30.      </>
  31.      )
  32. }

现在获取用户和获取文章列表的逻辑已经可以并行了,但是这样又导致 Articles 组件同其数据获取相关的逻辑分离,随着应用变得复杂后,这种方式可能会难以维护。同时第二个问题 “fetch-on-render” 还是没有解决。而 Suspense 的出现可以很好的解决这些问题,接下来就来看看是如何解决的。

Suspense 的使用

Suspense 用于数据获取

还是上面的例子,我们使用 Suspense 来改造一下:

  1. // Profile.js
  2. import React, {Suspense} from ‘react’
  3. import User from ‘./User’
  4. import Articles from ‘./Articles’
  5. export default function Profile() {
  6.      return (
  7.      <Suspense fallback={<p>Loading user…</p>}>
  8.          <User />
  9.          <Suspense fallback={<p>Loading articles…</p>}>
  10.          <Articles />
  11.          </Suspense>
  12.      </Suspense>
  13.      )
  14. }
  15. // Articles.js
  16. import React from ‘react’
  17. import {getArticlesResource} from ‘./resource’
  18. const articlesResource = getArticlesResource()
  19. const Articles = () => {
  20.      debugger
  21.      const articles = articlesResource.read()
  22.      return (
  23.      <ul>
  24.          {articles.map((article) => (
  25.          <li key={article.id}>
  26.              <h4>{article.title}</h4>
  27.              <p>{article.abstract}</p>
  28.          </li>
  29.          ))}
  30.      </ul>
  31.      )
  32. }
  33. // User.js
  34. import React from ‘react’
  35. import {getUserResource} from ‘./resource’
  36. const userResource = getUserResource()
  37. const User = () => {
  38.      const user = userResource.read()
  39.      return <h3>{user.name}</h3>
  40. }
  41. // resource.js
  42. export function wrapPromise(promise) {
  43.      let status = ‘pending’
  44.      let result
  45.      let suspender = promise.then(
  46.      (r) => {
  47.          debugger
  48.          status = ‘success’
  49.          result = r
  50.      },
  51.      (e) => {
  52.          status = ‘error’
  53.          result = e
  54.      }
  55.      )
  56.      return {
  57.      read() {
  58.          if (status === ‘pending’) {
  59.          throw suspender
  60.          } else if (status === ‘error’) {
  61.          throw result
  62.          } else if (status === ‘success’) {
  63.          return result
  64.          }
  65.      },
  66.      }
  67. }
  68. export function getArticles() {
  69.      return new Promise((resolve, reject) => {
  70.      const list = […new Array(10)].map((_, index) => ({
  71.          id: index,
  72.          title: `Title${index + 1}`,
  73.          abstract: `Abstract${index + 1}`,
  74.      }))
  75.      setTimeout(() => {
  76.          resolve(list)
  77.      }, 2000)
  78.      })
  79. }
  80. export function getUser() {
  81.      return new Promise((resolve, reject) => {
  82.      setTimeout(() => {
  83.          resolve({
  84.          name: ‘Ayou’,
  85.          age: 18,
  86.          vocation: ‘Program Ape’,
  87.          })
  88.      }, 3000)
  89.      })
  90. }
  91. export const getUserResource = () => {
  92.      return wrapPromise(getUser())
  93. }
  94. export const getArticlesResource = () => {
  95.      return wrapPromise(getArticles())
  96. }

首先,在 Profile.js 中开始引入 User 和 Articles 的时候就已经开始请求数据了,即 “Render-as-You-Fetch”(渲染的时候请求),且两者是并行的。当渲染到 User 组件的时候,由于此时接口请求还未返回,const user = userResource.read() 会抛出异常:

  1.      read() {
  2.      if (status === ‘pending’) {
  3.          throw suspender
  4.      } else if (status === ‘error’) {
  5.          throw result
  6.      } else if (status === ‘success’) {
  7.          return result
  8.      }
  9.      },

而 Suspense 组件的作用是,当发现其包裹的组件抛出异常且异常为 Promise 对象时,会渲染 fallback 中的内容,即 <p>Loading user...</p>。等到 Promise 对象 resolve 的时候会再次触发重新渲染,显示其包裹的内容,又因为获取文章列表的时间比用户短,所以这里会同时显示用户信息及其文章列表(具体过程后续会再进行分析)。这样,通过 Suspense 组件,我们就解决了前面的两个问题。

同时,使用 Suspense 还会有另外一个好处,假设我们现在改变我们的需求,允许用户信息和文章列表独立渲染,则使用 Suspense 重构起来会比较简单:

-1

而如果使用原来的方式,则需要修改的地方比较多:

-2

可见,使用 Suspense 会带来很多好处。当然,上文为了方便说明,写得非常简单,实际开发时会结合 Relay 这样的库来使用,由于这一款目前还处于试验阶段,所以暂时先不做过多的讨论。

Suspense 除了可以用于上面的数据获取这种场景外,还可以用来实现 Lazy Component

Lazy Component

  1. import React, {Suspense} from ‘react’
  2. const MyComp = React.lazy(() => import(‘./MyComp’))
  3. export default App() {
  4.      return (
  5.      <Suspense fallback={<p>Loading Component…</p>}>
  6.          <MyComp />
  7.      </Suspense>
  8.      )
  9. }

我们知道 import('./MyComp') 返回的是一个 Promise 对象,其 resolve 的是一个模块,既然如此那这样也是可以的:

  1. import React, {Suspense} from ‘react’
  2. const MyComp = React.lazy(
  3.      () =>
  4.      new Promise((resolve) =>
  5.          setTimeout(
  6.          () =>
  7.              resolve({
  8.              default: function MyComp() {
  9.                  return <div>My Comp</div>
  10.              },
  11.              }),
  12.          1000
  13.          )
  14.      )
  15. )
  16. export default function App() {
  17.      return (
  18.      <Suspense fallback={<p>Loading Component…</p>}>
  19.          <MyComp />
  20.      </Suspense>
  21.      )
  22. }

甚至,我们可以通过请求来获取 Lazy Component 的代码:

  1. import React, {Suspense} from ‘react’
  2. const MyComp = React.lazy(
  3.      () =>
  4.      new Promise(async (resolve) => {
  5.          const code = await fetch(‘http://xxxx’)
  6.          const module = {exports: {}}
  7.          Function(‘export, module’, code)(module.exports, module)
  8.          resolve({default: module.exports})
  9.      })
  10. )
  11. export default function App() {
  12.      return (
  13.      <Suspense fallback={<p>Loading Component…</p>}>
  14.          <MyComp />
  15.      </Suspense>
  16.      )
  17. }

这也是我们实现远程组件的基本原理。

原理

介绍了这么多关于 Suspense 的内容后,你一定很好奇它到底是如何实现的吧,我们先不研究 React 源码,先尝试自己实现一个 Suspense

  1. import React, {Component} from ‘react’
  2. export default class Suspense extends Component {
  3.      state = {
  4.      isLoading: false,
  5.      }
  6.      componentDidCatch(error, info) {
  7.      if (this._mounted) {
  8.          if (typeof error.then === ‘function’) {
  9.          this.setState({isLoading: true})
  10.          error.then(() => {
  11.              if (this._mounted) {
  12.              this.setState({isLoading: false})
  13.              }
  14.          })
  15.          }
  16.      }
  17.      }
  18.      componentDidMount() {
  19.      this._mounted = true
  20.      }
  21.      componentWillUnmount() {
  22.      this._mounted = false
  23.      }
  24.      render() {
  25.      const {children, fallback} = this.props
  26.      const {isLoading} = this.state
  27.      return isLoading ? fallback : children
  28.      }
  29. }

其核心原理就是利用了 “Error Boundary” 来捕获子组件中的抛出的异常,且如果抛出的异常为 Promise 对象,则在传入其 then 方法的回调中改变 state 触发重新渲染。

接下来,我们还是用上面的例子来分析一下整个过程:

  1. export default function Profile() {
  2.      return (
  3.      <Suspense fallback={<p>Loading user…</p>}>
  4.          <User />
  5.          <Suspense fallback={<p>Loading articles…</p>}>
  6.          <Articles />
  7.          </Suspense>
  8.      </Suspense>
  9.      )
  10. }

我们知道 React 在渲染时会构建 Fiber Tree,当处理到 User 组件时,React 代码中会捕获到异常:

  1. do {
  2.      try {
  3.      workLoopConcurrent()
  4.      break
  5.      } catch (thrownValue) {
  6.      handleError(root, thrownValue)
  7.      }
  8. } while (true)

-1

其中,异常处理函数 handleError 主要做两件事:

  1. throwException(
  2.      root,
  3.      erroredwork.return,
  4.      erroredWork,
  5.      thrownValue,
  6.      workInProgressRootRenderLanes
  7. )
  8. completeUnitOfWork(erroredWork)

其中,throwException 主要是往上找到最近的 Suspense 类型的 Fiber,并更新其 updateQueue

  1. const wakeables: Set&lt;Wakeable&gt; = (workInProgress.updateQueue: any)
  2. if (wakeables === null) {
  3.      const updateQueue = (new Set(): any)
  4.      updateQueue.add(wakeable) // wakeable 是 handleError(root, thrownValue) 中的 thrownValue,是一个 Promise 对象
  5.      workInProgress.updateQueue = updateQueue
  6. } else {
  7.      wakeables.add(wakeable)
  8. }

-4

而 completeUnitOfWork(erroredWork) 在React 源码解读之首次渲染流程中已经介绍过了,此处就不再赘述了。

render 阶段后,会形成如下所示的 Fiber 结构:

-5

之后会进入 commit 阶段,将 Fiber 对应的 DOM 插入到容器之中:

-6

注意到 Loading articles... 虽然也被插入了,但确是不可见的。

前面提到过 Suspense 的 updateQueue 中保存了 Promise 请求对象,我们需要在其 resolve 以后触发应用的重新渲染,这一步骤仍然是在 commit 阶段实现的:

  1. function commitWork(current: Fiber | null, finishedWork: Fiber): void {
  2.      
  3.      case SuspenseComponent: {
  4.      commitSuspenseComponent(finishedWork);
  5.      attachSuspenseRetryListeners(finishedWork);
  6.      return;
  7.      }
  8.      
  9. }
  1. function attachSuspenseRetryListeners(finishedWork: Fiber) {
  2.      // If this boundary just timed out, then it will have a set of wakeables.
  3.      // For each wakeable, attach a listener so that when it resolves, React
  4.      // attempts to re-render the boundary in the primary (pre-timeout) state.
  5.      const wakeables: Set<Wakeable> | null = (finishedWork.updateQueue: any)
  6.      if (wakeables !== null) {
  7.      finishedWork.updateQueue = null
  8.      let retryCache = finishedWork.stateNode
  9.      if (retryCache === null) {
  10.          retryCache = finishedWork.stateNode = new PossiblyWeakSet()
  11.      }
  12.      wakeables.forEach((wakeable) => {
  13.          // Memoize using the boundary fiber to prevent redundant listeners.
  14.          let retry = resolveRetryWakeable.bind(null, finishedWork, wakeable)
  15.          if (!retryCache.has(wakeable)) {
  16.          if (enableSchedulerTracing) {
  17.              if (wakeable.__reactDoNotTraceInteractions !== true) {
  18.              retry = Schedule_tracing_wrap(retry)
  19.              }
  20.          }
  21.          retryCache.add(wakeable)
  22.          // promise resolve 了以后触发 react 的重新渲染
  23.          wakeable.then(retry, retry)
  24.          }
  25.      })
  26.      }
  27. }

总结

本文介绍了 Suspense 提出的背景、使用方式以及原理,从文中可看出 Suspense 用于数据获取对我们的开发方式将是一个巨大的影响,但是目前还处在实验阶段,所以留给“中国队”的时间还是很充足的。

以上就是React 之 Suspense提出的背景及使用详解的详细内容,更多关于React Suspense使用背景的资料请关注我们其它相关文章!

标签

发表评论