{"id":1170,"date":"2022-06-19T21:04:16","date_gmt":"2022-06-19T13:04:16","guid":{"rendered":"https:\/\/sora.sound.moe\/?p=1170"},"modified":"2022-06-19T21:04:16","modified_gmt":"2022-06-19T13:04:16","slug":"react-18-suspense-for-data-fetching","status":"publish","type":"post","link":"https:\/\/sora.sound.moe\/?p=1170","title":{"rendered":"React 18: Suspense for Data Fetching"},"content":{"rendered":"\n<!--more-->\n\n\n\n<p>\u65e9\u5728 React 16.6\uff0cReact \u5c31\u5f15\u5165\u4e86 <code>Suspense<\/code> \u7ec4\u4ef6\uff0c\u7528\u4e8e\u61d2\u52a0\u8f7d React \u7ec4\u4ef6\uff08\u4f7f\u7528 <code>React.lazy<\/code>\uff09\u3002\u4f46\u76f4\u5230 React 18\uff0c\u5b83\u624d\u6b63\u5f0f\u652f\u6301\u4e86\u66f4\u5e7f\u6cdb\u7684\u7528\u9014\uff1a\u6570\u636e\u52a0\u8f7d\u3002<\/p>\n\n\n\n<p>\u5c3d\u7ba1\uff0c\u5728 React 18 \u7684\u6587\u6863\u4e2d\uff0c\u8fd8\u662f\u63d0\u5230\uff0c\u5f53\u524d\u7248\u672c\u7684 Suspense \u7684\u552f\u4e00\u7528\u9014\u662f\u61d2\u52a0\u8f7d\u7ec4\u4ef6\uff0c\u4f46\u5b83\u4e5f\u63d0\u5230\u4e86\u4e00\u4e9b\u6846\u67b6\u4e2d\u5df2\u7ecf\u7528\u4e8e\u6570\u636e\u52a0\u8f7d\uff0c\u90a3\u4e48\u5177\u4f53\u662f\u600e\u4e48\u505a\u7684\u5462\u3002<\/p>\n\n\n\n<blockquote class=\"wp-block-quote\"><p>Today, lazy loading components is the&nbsp;<strong>only<\/strong>&nbsp;use case supported by&nbsp;<code>&lt;React.Suspense&gt;<\/code>[1]:<\/p><\/blockquote>\n\n\n\n<p>\u5728 JavaScript \u4e2d\uff0c\u4efb\u4f55\u7c7b\u578b\u7684\u503c\u90fd\u53ef\u4ee5\u88ab <code>throw<\/code> \u5e76\u88ab\u5916\u5c42 <code>catch<\/code>\uff0cReact \u4f7f\u7528\u4e86\u8fd9\u4e2a\u7279\u6027\uff0c\u8ba9 <code>Suspense<\/code> \u53ef\u4ee5\u6355\u6349\u5185\u90e8\u629b\u51fa\u7684\u4efb\u610f <code><strong>Promise<\/strong><\/code>\u3002\u8fd9\u4e2a\u673a\u5236\u4e0e Error Boundary \u76f8\u4f3c\uff0c\u4e5f\u6709\u4eba\u79f0\u4e4b\u4e3a Promise Boundary\u3002<\/p>\n\n\n\n<p>\u90a3\u4e48\u5177\u4f53\u662f\u600e\u4e48\u64cd\u4f5c\u5462\uff0c\u6765\u770b\u4e00\u4e2a\u4f8b\u5b50<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>import { Suspense } from \"react\";\n\nlet isLoaded = false;\n\nconst Content = () =&gt; {\n  if (!isLoaded) {\n    throw new Promise((resolve) =&gt; {\n      setTimeout(() =&gt; {\n        isLoaded = true;\n        resolve();\n      }, 2000);\n    });\n  }\n  return &lt;div&gt;111&lt;\/div&gt;;\n};\n\nexport default function App() {\n  return (\n    &lt;div id=\"App\"&gt;\n      &lt;Suspense fallback={&lt;div&gt;Loading...&lt;\/div&gt;}&gt;\n        &lt;Content \/&gt;\n      &lt;\/Suspense&gt;\n    &lt;\/div&gt;\n  );\n}\n<\/code><\/pre>\n\n\n\n<p>\u8fd9\u4e2a\u4f8b\u5b50\u7684\u7ed3\u679c\u662f\uff0c\u5c06\u4f1a\u5148\u770b\u5230 Loading&#8230;\uff0c\u4e24\u79d2\u540e\u91cd\u65b0\u6e32\u67d3\u4e3a111\u3002\u8fd9\u91cc\u7684\u4e24\u79d2\u5ef6\u8fdf\u53ef\u4ee5\u88ab\u66ff\u6362\u4e3a\u4efb\u610f\u5f02\u6b65\u4efb\u52a1\uff0c\u4f8b\u5982\u4ece API \u83b7\u53d6\u6570\u636e\u7b49\u3002<\/p>\n\n\n\n<p>\u5176\u5b9e\u4e00\u4e9b\u6570\u636e\u8bf7\u6c42\u5e93\u5df2\u7ecf\u652f\u6301\u4e86\u8fd9\u4e00\u7279\u6027\uff0c\u4f8b\u5982 useSWR \u652f\u6301 suspense \u6a21\u5f0f\uff0c\u5176\u6838\u5fc3\u539f\u7406\u548c\u8fd9\u4e2a\u4f8b\u5b50\u662f\u4e00\u6837\u7684\u3002<\/p>\n\n\n\n<p>\u4e0b\u9762\u4ece React \u6e90\u7801\u5206\u6790\u4e00\u4e0b Promise \u662f\u600e\u4e48\u88ab Suspense \u5904\u7406\u7684<\/p>\n\n\n\n<p>\u9996\u5148\uff0c\u5f53\u4e00\u4e2a\u9519\u8bef\u88ab\u629b\u51fa\u65f6\uff0c\u4f1a\u88ab <code>handleError<\/code> \u65b9\u6cd5\u7edf\u4e00\u6355\u6349\uff0c\u5224\u65ad\u629b\u51fa\u7684\u503c\u662f\u5426\u4e3a\u4e00\u4e2a Promise\uff0c\u5982\u679c\u662f\uff0c\u5c06\u4f1a\u628a\u7ec4\u4ef6\u6807\u8bb0\u4e3a Suspended \u72b6\u6001\u3002\u968f\u540e\uff0c\u901a\u8fc7\u7edf\u4e00\u7684 <code>throwError<\/code> \u65b9\u6cd5\u629b\u51fa\u3002<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>if (\n  thrownValue !== null &amp;&amp;\n  typeof thrownValue === 'object' &amp;&amp;\n  typeof thrownValue.then === 'function'\n) {\n  const wakeable: Wakeable = (thrownValue: any);\n  markComponentSuspended(\n    erroredWork,\n    wakeable,\n    workInProgressRootRenderLanes,\n  );\n} else {\n  \/\/ \u9519\u8bef\u5904\u7406..\u7565\n}\nthrowException(\n  root,\n  erroredWork.return,\n  erroredWork,\n  thrownValue,\n  workInProgressRootRenderLanes,\n);<\/code><\/pre>\n\n\n\n<p>\u5728 <code>throwError<\/code> \u65b9\u6cd5\u4e2d\uff0c\u9488\u5bf9\u629b\u51fa\u7684\u662f Promise \u7684\u60c5\u51b5\uff0c\u4f1a\u627e\u5230\u6700\u8fd1\u7684 Suspense Boundary\uff0c\u8c03\u5ea6 Suspense Boundary \u6e32\u67d3 fallback \u72b6\u6001\u3002\u8fd9\u79cd\u629b\u51fa\u7684 Promise \u5728 React \u5185\u90e8\u88ab\u79f0\u4e3a Wakeable\u3002<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>const suspenseBoundary = getNearestSuspenseBoundaryToCapture(returnFiber);\nif (suspenseBoundary !== null) {\n  suspenseBoundary.flags &amp;= ~ForceClientRender;\n  markSuspenseBoundaryShouldCapture(\n    suspenseBoundary,\n    returnFiber,\n    sourceFiber,\n    root,\n    rootRenderLanes,\n  );\n  \/\/ We only attach ping listeners in concurrent mode. Legacy Suspense always\n  \/\/ commits fallbacks synchronously, so there are no pings.\n  if (suspenseBoundary.mode &amp; ConcurrentMode) {\n    attachPingListener(root, wakeable, rootRenderLanes);\n  }\n  attachRetryListener(suspenseBoundary, root, wakeable, rootRenderLanes);\n  return;\n}<\/code><\/pre>\n\n\n\n<p>\u540c\u65f6\uff0c\u4f1a\u9488\u5bf9\u8fd9\u4e9b Wakeable \u6ce8\u518c\u4e00\u4e9b\u94a9\u5b50\uff0c\u5728 Promise \u88ab resolve \u7684\u65f6\u5019\u83b7\u5f97\u901a\u77e5\u3002\u8fd9\u91cc\u5206\u4e3a RetryListener \u548c PingListener\u3002\u5177\u4f53\u7684\u533a\u522b\u662f\u4ec0\u4e48\u5462<\/p>\n\n\n\n<p>PingListener \u9488\u5bf9\u7684\u662f Concurrent Render \u6a21\u5f0f\u4e0b\uff0c\u53ef\u80fd fallback \u8fd8\u672a\u6e32\u67d3\u6216\u6b63\u5728\u6e32\u67d3\uff0cPromise \u5c31\u5df2\u7ecf\u8fd4\u56de\u4e86\u7ed3\u679c\uff0c\u8fd9\u79cd\u60c5\u51b5\u4e0b\u4f1a\u8fdb\u884c\u91cd\u65b0\u6e32\u67d3\u3002<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>if (\nworkInProgressRoot === root &amp;&amp;\nisSubsetOfLanes(workInProgressRootRenderLanes, pingedLanes)\n) {\n\/\/ Received a ping at the same priority level at which we're currently\n\/\/ rendering. We might want to restart this render. This should mirror\n\/\/ the logic of whether or not a root suspends once it completes.\n\n\/\/ TODO: If we're rendering sync either due to Sync, Batched or expired,\n\/\/ we should probably never restart.\n\n\/\/ If we're suspended with delay, or if it's a retry, we'll always suspend\n\/\/ so we can always restart.\nif (\n  workInProgressRootExitStatus === RootSuspendedWithDelay ||\n  (workInProgressRootExitStatus === RootSuspended &amp;&amp;\n    includesOnlyRetries(workInProgressRootRenderLanes) &amp;&amp;\n    now() - globalMostRecentFallbackTime &lt; FALLBACK_THROTTLE_MS)\n) {\n  \/\/ Restart from the root.\n  prepareFreshStack(root, NoLanes);\n} else {\n  \/\/ Even though we can't restart right now, we might get an\n  \/\/ opportunity later. So we mark this render as having a ping.\n  workInProgressRootPingedLanes = mergeLanes(\n    workInProgressRootPingedLanes,\n    pingedLanes,\n  );\n}<\/code><\/pre>\n\n\n\n<p>\u800c RetryListener \u5219\u9002\u7528\u4e8e fallback \u5df2\u7ecf\u88ab\u6e32\u67d3\u7684\u60c5\u51b5\uff0c\u6b64\u65f6\u4f1a\u5c06\u8be5 Wakeable \u52a0\u5165\u7ec4\u4ef6\u7684 updateQueue \u5f53 Promise \u8fd4\u56de\u65f6\uff0cReact \u4f1a\u8c03\u5ea6\u8be5\u7ec4\u4ef6\u91cd\u65b0\u6e32\u67d3\u3002<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>function attachRetryListener(\n  suspenseBoundary: Fiber,\n  root: FiberRoot,\n  wakeable: Wakeable,\n  lanes: Lanes,\n) {\n  \/\/ Retry listener\n  \/\/\n  \/\/ If the fallback does commit, we need to attach a different type of\n  \/\/ listener. This one schedules an update on the Suspense boundary to turn\n  \/\/ the fallback state off.\n  \/\/\n  \/\/ Stash the wakeable on the boundary fiber so we can access it in the\n  \/\/ commit phase.\n  \/\/\n  \/\/ When the wakeable resolves, we'll attempt to render the boundary\n  \/\/ again (\"retry\").\n  const wakeables: Set&lt;Wakeable&gt; | null = (suspenseBoundary.updateQueue: any);\n  if (wakeables === null) {\n    const updateQueue = (new Set(): any);\n    updateQueue.add(wakeable);\n    suspenseBoundary.updateQueue = updateQueue;\n  } else {\n    wakeables.add(wakeable);\n  }\n}<\/code><\/pre>\n\n\n\n<p>\u6ce8\u610f\u8fd9\u91cc\u8fd8\u6ca1\u6267\u884c listener \u7684\u7ed1\u5b9a\uff0c\u800c\u662f\u5230 commit \u9636\u6bb5\u518d\u64cd\u4f5c<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>case SuspenseComponent: {\n  \/\/ .. \u7701\u7565\n\n  if (flags &amp; Update) {\n    try {\n      commitSuspenseCallback(finishedWork);\n    } catch (error) {\n      captureCommitPhaseError(finishedWork, finishedWork.return, error);\n    }\n    attachSuspenseRetryListeners(finishedWork);\n  }\n  return;\n}<\/code><\/pre>\n\n\n\n<p>\u7b49\u5230\u4efb\u610f Wakeable \u88ab resolve \u7684\u65f6\u5019\uff0c\u8c03\u5ea6\u4e00\u6b21\u65b0\u7684\u6e32\u67d3<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>function resolveRetryWakeable(boundaryFiber: Fiber, wakeable: Wakeable) {\n  let retryLane = NoLane; \/\/ Default\n  let retryCache: WeakSet&lt;Wakeable&gt; | Set&lt;Wakeable&gt; | null;\n  switch (boundaryFiber.tag) {\n    case SuspenseComponent:\n      retryCache = boundaryFiber.stateNode;\n      const suspenseState: null | SuspenseState = boundaryFiber.memoizedState;\n      if (suspenseState !== null) {\n        retryLane = suspenseState.retryLane;\n      }\n      break;\n\n   \/\/ .. \u7701\u7565\n  }\n\n  \/\/ .. \u7701\u7565\n\n  retryTimedOutBoundary(boundaryFiber, retryLane);\n}\n\nfunction retryTimedOutBoundary(boundaryFiber: Fiber, retryLane: Lane) {\n  \/\/ The boundary fiber (a Suspense component or SuspenseList component)\n  \/\/ previously was rendered in its fallback state. One of the promises that\n  \/\/ suspended it has resolved, which means at least part of the tree was\n  \/\/ likely unblocked. Try rendering again, at a new lanes.\n  if (retryLane === NoLane) {\n    \/\/ TODO: Assign this to `suspenseState.retryLane`? to avoid\n    \/\/ unnecessary entanglement?\n    retryLane = requestRetryLane(boundaryFiber);\n  }\n  \/\/ TODO: Special case idle priority?\n  const eventTime = requestEventTime();\n  const root = enqueueConcurrentRenderForLane(boundaryFiber, retryLane);\n  if (root !== null) {\n    markRootUpdated(root, retryLane, eventTime);\n    ensureRootIsScheduled(root, eventTime);\n  }\n}<\/code><\/pre>\n\n\n\n<p>\u81f3\u6b64\uff0cSuspense \u5de5\u4f5c\u7684\u5927\u4f53\u6d41\u7a0b\u5df2\u7ecf\u6e05\u6670\u3002\u4e0b\u9762\u662f\u4e00\u4e9b\u5177\u4f53\u4f7f\u7528\u65f6\u9700\u8981\u6ce8\u610f\u7684\u5730\u65b9<\/p>\n\n\n\n<ol><li>\u4f60\u53ef\u80fd\u6ce8\u610f\u5230\uff0c\u6700\u5f00\u59cb\u7684\u4f8b\u5b50\u4e2d\uff0cisLoaded \u653e\u5728\u4e86\u7ec4\u4ef6\u5916\uff0c\u8fd9\u91cc\u4e3a\u4ec0\u4e48\u4e0d\u7528\u6211\u4eec\u66f4\u719f\u6089\u7684 <code>useRef<\/code> \u4fdd\u5b58\u72b6\u6001\u5462\u3002\u56e0\u4e3a Suspense \u7ec4\u4ef6\u5e76\u4e0d\u4f1a\u4fdd\u5b58\u4efb\u4f55\u72b6\u6001\uff0c\u91cd\u65b0\u6e32\u67d3\u65f6\u5c06\u5b8c\u5168\u91cd\u65b0\u6e32\u67d3\uff0c\u65e0\u8bba\u662f <code>useState<\/code> \u8fd8\u662f <code>useMemo<\/code> \u4e4b\u7c7b\u7684 Hooks \u90fd\u4e0d\u4f1a\u751f\u6548\uff0c<code>useEffect<\/code> \u5728 suspended \u72b6\u6001\u4e0d\u4f1a\u88ab\u6267\u884c\u3002\u5177\u4f53\u53ef\u4ee5\u53c2\u8003\uff1a<a href=\"https:\/\/github.com\/facebook\/react\/issues\/14563\">https:\/\/github.com\/facebook\/react\/issues\/14563<\/a>\u3002\u56e0\u6b64\uff0c\u72b6\u6001\u5fc5\u987b\u88ab\u4fdd\u5b58\u5728\u5916\u90e8\uff0c\u53ef\u4ee5\u4f7f\u7528\u4e0a\u56de\u6587\u7ae0\u63d0\u5230\u7684 <code>useExternalStore<\/code>\uff08useSWR \u5c31\u662f\u8fd9\u4e48\u505a\u7684\uff09\u3002<\/li><li>\u5f53\u540c\u4e00\u4f4d\u7f6e\u5b58\u5728\u591a\u4e2a Suspense \u7ec4\u4ef6\u65f6\uff0c\u5fc5\u987b\u8003\u8651\u7ec4\u4ef6\u5207\u6362\u65f6\u662f\u5426\u4f1a\u91cd\u65b0\u6e32\u67d3\u51fa fallback \u72b6\u6001\u3002\u4f8b\u5982\uff0c\u4e00\u4e2a Tab \u5217\u8868\u4e2d\u591a\u4e2a Tab \u90fd\u662f\u61d2\u52a0\u8f7d\u7ec4\u4ef6\uff0c\u5e76\u88ab Suspense \u5305\u88f9\uff0c\u5207\u6362 Tab \u65f6\u6211\u4eec\u53ef\u80fd\u4e0d\u5e0c\u671b\u518d\u663e\u793a\u521d\u59cb\u7684 Loading \u72b6\u6001\uff0c\u8fd9\u65f6\u5019\u53ef\u4ee5\u914d\u5408 <code>startTransition<\/code> \u8fdb\u884c\u5207\u6362\u3002\u53ef\u4ee5\u53c2\u8003\uff1a<a href=\"https:\/\/github.com\/reactwg\/react-18\/discussions\/94\">https:\/\/github.com\/reactwg\/react-18\/discussions\/94<\/a>\u3002<\/li><\/ol>\n\n\n\n<p>\u7ecf\u8fc7\u4e00\u5b9a\u7684\u5b9e\u8df5\uff0c\u6211\u4eec\u53ef\u4ee5\u53d1\u73b0\u5f53\u524d\u5229\u7528 Suspense \u8fdb\u884c\u6570\u636e\u52a0\u8f7d\u5176\u5b9e\u662f\u6bd4\u8f83\u7b80\u964b\u7684\u3002React \u4e5f\u4f1a\u5728 18 \u7684\u540e\u7eed\u7248\u672c\u589e\u52a0\u66f4\u591a\u7528\u4e8e\u6570\u636e\u52a0\u8f7d\u7684\u529f\u80fd\uff0c\u53ef\u4ee5\u6301\u7eed\u5173\u6ce8\u4e00\u4e0b\u3002<\/p>\n\n\n\n<h2>\u53c2\u8003<\/h2>\n\n\n\n<ol><li>https:\/\/reactjs.org\/docs\/react-api.html#reactsuspense<\/li><\/ol>\n\n\n\n<h3>\u5ef6\u4f38\u9605\u8bfb<\/h3>\n\n\n\n<ol><li>React Suspense RFC: <a href=\"https:\/\/github.com\/reactjs\/rfcs\/blob\/main\/text\/0213-suspense-in-react-18.md\">https:\/\/github.com\/reactjs\/rfcs\/blob\/main\/text\/0213-suspense-in-react-18.md<\/a><\/li><li>Suspense for Data Fetching \u5b9e\u4f8b\u6559\u5b66\uff1a<a href=\"https:\/\/blog.logrocket.com\/react-suspense-data-fetching\/\">https:\/\/blog.logrocket.com\/react-suspense-data-fetching\/<\/a><\/li><\/ol>\n","protected":false},"excerpt":{"rendered":"","protected":false},"author":1,"featured_media":0,"comment_status":"open","ping_status":"open","sticky":false,"template":"","format":"standard","meta":[],"categories":[2],"tags":[],"uagb_featured_image_src":{"full":false,"thumbnail":false,"medium":false,"medium_large":false,"large":false,"1536x1536":false,"2048x2048":false,"twentyseventeen-featured-image":false,"twentyseventeen-thumbnail-avatar":false},"uagb_author_info":{"display_name":"Sora","author_link":"https:\/\/sora.sound.moe\/?author=1"},"uagb_comment_info":0,"uagb_excerpt":null,"_links":{"self":[{"href":"https:\/\/sora.sound.moe\/index.php?rest_route=\/wp\/v2\/posts\/1170"}],"collection":[{"href":"https:\/\/sora.sound.moe\/index.php?rest_route=\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/sora.sound.moe\/index.php?rest_route=\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/sora.sound.moe\/index.php?rest_route=\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"https:\/\/sora.sound.moe\/index.php?rest_route=%2Fwp%2Fv2%2Fcomments&post=1170"}],"version-history":[{"count":0,"href":"https:\/\/sora.sound.moe\/index.php?rest_route=\/wp\/v2\/posts\/1170\/revisions"}],"wp:attachment":[{"href":"https:\/\/sora.sound.moe\/index.php?rest_route=%2Fwp%2Fv2%2Fmedia&parent=1170"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/sora.sound.moe\/index.php?rest_route=%2Fwp%2Fv2%2Fcategories&post=1170"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/sora.sound.moe\/index.php?rest_route=%2Fwp%2Fv2%2Ftags&post=1170"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}