React v18.0 新特性官方文檔[中英文對照]

React 18 is now available on npm!

反應18現(xiàn)在可以在 npm 上使用芹扭!

In our last post, we shared step-by-step instructions for upgrading your app to React 18. In this post, we’ll give an overview of what’s new in React 18, and what it means for the future.

在我們上一篇文章中,我們分享了將你的應用升級到 React 18的步驟說明。在這篇文章中,我們將概述什么是新的反應18,以及它對未來的意義懈凹。

Our latest major version includes out-of-the-box improvements like automatic batching, new APIs like startTransition, and streaming server-side rendering with support for Suspense.

我們最新的主要版本包括開箱即用的改進,如自動批處理悄谐,新的 api介评,如 startTransition,以及支持懸念的流服務器端渲染。

Many of the features in React 18 are built on top of our new concurrent renderer, a behind-the-scenes change that unlocks powerful new capabilities. Concurrent React is opt-in — it’s only enabled when you use a concurrent feature — but we think it will have a big impact on the way people build applications.

React 18中的許多特性是在我們新的并發(fā)呈現(xiàn)程序之上構(gòu)建的们陆,這是一個幕后的更改寒瓦,解鎖了強大的新功能。Concurrent React 是自愿加入的坪仇,只有在使用并發(fā)功能時才會啟用杂腰,但我們認為它將對人們構(gòu)建應用程序的方式產(chǎn)生重大影響。

We’ve spent years researching and developing support for concurrency in React, and we’ve taken extra care to provide a gradual adoption path for existing users. Last summer, we formed the React 18 Working Group to gather feedback from experts in the community and ensure a smooth upgrade experience for the entire React ecosystem.

我們花了多年時間研究和開發(fā) React 中對并發(fā)性的支持椅文,并且我們特別注意為現(xiàn)有用戶提供一個漸進的采用路徑喂很。去年夏天,我們成立了 React 18工作組雾袱,以收集社區(qū)專家的反饋恤筛,確保整個 React 生態(tài)系統(tǒng)的順利升級體驗官还。

In case you missed it, we shared a lot of this vision at React Conf 2021:

如果你沒有注意到芹橡,我們在 React Conf 2021上分享了很多這樣的愿景:

Below is a full overview of what to expect in this release, starting with Concurrent Rendering.

下面是對這個版本中所期望的內(nèi)容的全面概述望伦,從并發(fā)呈現(xiàn)開始林说。

Note for React Native users: React 18 will ship in React Native with the New React Native Architecture. For more information, see the React Conf keynote here.

注意: React Native 用戶: React 18將發(fā)布在 React Native with the New React Native Architecture。更多信息屯伞,請參見 React Conf 主旨腿箩。

What is Concurrent React? 什么是并發(fā)反應?

The most important addition in React 18 is something we hope you never have to think about: concurrency. We think this is largely true for application developers, though the story may be a bit more complicated for library maintainers.

第18個反應中最重要的增加是我們希望你永遠不必考慮的東西: 并發(fā)性劣摇。我們認為這對于應用程序開發(fā)人員來說基本上是正確的珠移,盡管這個故事對于庫維護人員來說可能有點復雜。

Concurrency is not a feature, per se. It’s a new behind-the-scenes mechanism that enables React to prepare multiple versions of your UI at the same time. You can think of concurrency as an implementation detail — it’s valuable because of the features that it unlocks. React uses sophisticated techniques in its internal implementation, like priority queues and multiple buffering. But you won’t see those concepts anywhere in our public APIs.

并發(fā)本身并不是一個特性末融。這是一種新的幕后機制钧惧,允許 React 同時準備多個 UI 版本。你可以把并發(fā)看作是一種實現(xiàn)細節(jié)ーー它的價值在于它所解鎖的特性勾习。React 在其內(nèi)部實現(xiàn)中使用復雜的技術(shù)浓瞪,如優(yōu)先級隊列和多緩沖。但是在我們的公共 api 中你不會看到這些概念巧婶。

When we design APIs, we try to hide implementation details from developers. As a React developer, you focus on what you want the user experience to look like, and React handles how to deliver that experience. So we don’t expect React developers to know how concurrency works under the hood.

當我們設(shè)計 api 時乾颁,我們試圖對開發(fā)者隱藏實現(xiàn)細節(jié)。作為一個 React 開發(fā)人員艺栈,你專注于你想要的用戶體驗是什么樣的英岭,React 處理如何提供這種體驗。所以我們不指望 React 開發(fā)人員知道并發(fā)性是如何工作的湿右。

However, Concurrent React is more important than a typical implementation detail — it’s a foundational update to React’s core rendering model. So while it’s not super important to know how concurrency works, it may be worth knowing what it is at a high level.

然而巴席,Concurrent React 比典型的實現(xiàn)細節(jié)更重要ーー它是 React 核心渲染模型的基礎(chǔ)更新。所以诅需,雖然知道并發(fā)是如何工作的并不是特別重要漾唉,但是在高層次上知道它是什么可能是值得的荧库。

A key property of Concurrent React is that rendering is interruptible. When you first upgrade to React 18, before adding any concurrent features, updates are rendered the same as in previous versions of React — in a single, uninterrupted, synchronous transaction. With synchronous rendering, once an update starts rendering, nothing can interrupt it until the user can see the result on screen.

Concurrent React 的一個關(guān)鍵屬性是呈現(xiàn)是可中斷的。當您第一次升級到 React 18時赵刑,在添加任何并發(fā)特性之前分衫,在一個單一的、不間斷的般此、同步的事務中蚪战,所呈現(xiàn)的更新與 React 的以前版本相同。使用同步呈現(xiàn)铐懊,一旦更新開始呈現(xiàn)邀桑,任何東西都不能中斷它,直到用戶可以在屏幕上看到結(jié)果科乎。

In a concurrent render, this is not always the case. React may start rendering an update, pause in the middle, then continue later. It may even abandon an in-progress render altogether. React guarantees that the UI will appear consistent even if a render is interrupted. To do this, it waits to perform DOM mutations until the end, once the entire tree has been evaluated. With this capability, React can prepare new screens in the background without blocking the main thread. This means the UI can respond immediately to user input even if it’s in the middle of a large rendering task, creating a fluid user experience.

在并發(fā)渲染中壁畸,情況并非總是如此。反應可能開始呈現(xiàn)一個更新茅茂,暫停在中間捏萍,然后繼續(xù)以后。它甚至可能完全放棄正在進行的渲染空闲。作出反應可以保證令杈,即使渲染被中斷,UI 也會顯示出一致性碴倾。為了做到這一點逗噩,它等待執(zhí)行 DOM 變換,直到最后跌榔,即評估完整個樹之后异雁。有了這個功能,React 可以在后臺準備新的屏幕矫户,而不會阻塞主線程片迅。這意味著 UI 可以立即響應用戶輸入,即使它處于一個大型渲染任務的中間皆辽,創(chuàng)建一個流暢的用戶體驗柑蛇。

Another example is reusable state. Concurrent React can remove sections of the UI from the screen, then add them back later while reusing the previous state. For example, when a user tabs away from a screen and back, React should be able to restore the previous screen in the same state it was in before. In an upcoming minor, we’re planning to add a new component called <Offscreen> that implements this pattern. Similarly, you’ll be able to use Offscreen to prepare new UI in the background so that it’s ready before the user reveals it.

另一個例子是可重用狀態(tài)。Concurrent React 可以從屏幕上刪除 UI 的部分驱闷,然后在重用之前的狀態(tài)時將它們添加回來耻台。例如,當用戶選項卡遠離屏幕并返回時空另,React 應該能夠?qū)⑶耙粋€屏幕恢復到與之前相同的狀態(tài)盆耽。在即將到來的次要版本中,我們計劃添加一個名為 < offscreen > 的新組件來實現(xiàn)這個模式。類似地摄杂,你可以使用 Offscreen 在后臺準備新的用戶界面坝咐,這樣在用戶顯示之前就可以了。

Concurrent rendering is a powerful new tool in React and most of our new features are built to take advantage of it, including Suspense, transitions, and streaming server rendering. But React 18 is just the beginning of what we aim to build on this new foundation.

并發(fā)渲染是 React 中一個強大的新工具析恢,我們的大多數(shù)新功能都是為了利用它而建立的墨坚,包括懸念、轉(zhuǎn)場和媒體伺服器渲染映挂。但是18號反應僅僅是我們在這個新基礎(chǔ)上的目標的開始泽篮。

Gradually Adopting Concurrent Features 逐步采用并行特性

Technically, concurrent rendering is a breaking change. Because concurrent rendering is interruptible, components behave slightly differently when it is enabled.

從技術(shù)上講,并發(fā)呈現(xiàn)是一個破壞性的變化柑船。因為并發(fā)呈現(xiàn)是可中斷的帽撑,所以當啟用它時,組件的行為稍有不同鞍时。

In our testing, we’ve upgraded thousands of components to React 18. What we’ve found is that nearly all existing components “just work” with concurrent rendering, without any changes. However, some of them may require some additional migration effort. Although the changes are usually small, you’ll still have the ability to make them at your own pace. The new rendering behavior in React 18 is only enabled in the parts of your app that use new features.

在我們的測試中亏拉,我們將數(shù)千個組件升級到了 React 18。我們發(fā)現(xiàn)寸癌,幾乎所有現(xiàn)有的組件在并發(fā)呈現(xiàn)時“正常工作”专筷,沒有任何更改弱贼。但是蒸苇,其中一些可能需要一些額外的遷移工作。雖然這些變化通常很小吮旅,但是你仍然有能力按照自己的節(jié)奏來完成它們溪烤。在 React 18中新的渲染行為只在應用程序中使用新特性的部分啟用。

The overall upgrade strategy is to get your application running on React 18 without breaking existing code. Then you can gradually start adding concurrent features at your own pace. You can use <StrictMode> to help surface concurrency-related bugs during development. Strict Mode doesn’t affect production behavior, but during development it will log extra warnings and double-invoke functions that are expected to be idempotent. It won’t catch everything, but it’s effective at preventing the most common types of mistakes.

總體升級策略是在不破壞現(xiàn)有代碼的情況下庇勃,在 React 18上運行應用程序檬嘀。然后你就可以開始按照自己的節(jié)奏逐步添加并發(fā)特性。您可以在開發(fā)過程中使用 < strictmode > 來幫助解決表面上與并發(fā)相關(guān)的錯誤责嚷。Strict Mode 不影響生產(chǎn)行為鸳兽,但是在開發(fā)過程中,它將記錄額外的警告和雙重調(diào)用函數(shù)罕拂,這些函數(shù)應該是冪等的揍异。它不會捕捉到所有的信息,但是它可以有效地防止最常見的錯誤爆班。

After you upgrade to React 18, you’ll be able to start using concurrent features immediately. For example, you can use startTransition to navigate between screens without blocking user input. Or useDeferredValue to throttle expensive re-renders.

升級到 React 18之后衷掷,您就可以立即開始使用并發(fā)特性了。例如柿菩,您可以使用 startTransition 在屏幕之間導航戚嗅,而不會阻塞用戶輸入。或者使用 deferredvalue 來抑制昂貴的重新呈現(xiàn)懦胞。

However, long term, we expect the main way you’ll add concurrency to your app is by using a concurrent-enabled library or framework. In most cases, you won’t interact with concurrent APIs directly. For example, instead of developers calling startTransition whenever they navigate to a new screen, router libraries will automatically wrap navigations in startTransition.

但是替久,從長遠來看,我們希望您為應用程序添加并發(fā)性的主要方式是使用并發(fā)啟用的庫或框架躏尉。在大多數(shù)情況下侣肄,您不會直接與并發(fā) api 交互。例如醇份,與開發(fā)人員在導航到新屏幕時調(diào)用 startTransition 不同稼锅,路由器庫將在 startTransition 中自動包裝導航。

It may take some time for libraries to upgrade to be concurrent compatible. We’ve provided new APIs to make it easier for libraries to take advantage of concurrent features. In the meantime, please be patient with maintainers as we work to gradually migrate the React ecosystem.

庫升級到并發(fā)兼容可能需要一些時間僚纷。我們提供了新的 api矩距,使得庫更容易利用并發(fā)特性。與此同時怖竭,在我們逐步遷移反應生態(tài)系統(tǒng)的過程中锥债,請對維護者保持耐心。

For more info, see our previous post: How to upgrade to React 18.

更多信息痊臭,請看我們之前的帖子: 如何升級到 React 18哮肚。

Suspense in Data Frameworks 數(shù)據(jù)框架中的懸念

In React 18, you can start using Suspense for data fetching in opinionated frameworks like Relay, Next.js, Hydrogen, or Remix. Ad hoc data fetching with Suspense is technically possible, but still not recommended as a general strategy.

在第18個反應中,您可以開始在諸如 Relay广匙、 Next.js允趟、 Hydrogen 或 Remix 等固執(zhí)的框架中使用暫停來獲取數(shù)據(jù)。使用暫記獲取特定數(shù)據(jù)在技術(shù)上是可行的鸦致,但是仍然不推薦作為一般策略潮剪。

In the future, we may expose additional primitives that could make it easier to access your data with Suspense, perhaps without the use of an opinionated framework. However, Suspense works best when it’s deeply integrated into your application’s architecture: your router, your data layer, and your server rendering environment. So even long term, we expect that libraries and frameworks will play a crucial role in the React ecosystem.

將來,我們可能會公開額外的原語分唾,這些原語可以使得使用懸念更容易地訪問數(shù)據(jù)抗碰,也許不需要使用固執(zhí)的框架。然而绽乔,懸念在深度集成到應用程序的體系結(jié)構(gòu)(路由器弧蝇、數(shù)據(jù)層和服務器呈現(xiàn)環(huán)境)中時效果最好。因此折砸,即使從長遠來看看疗,我們期望圖書館和框架將在 React 生態(tài)系統(tǒng)中發(fā)揮關(guān)鍵作用。

As in previous versions of React, you can also use Suspense for code splitting on the client with React.lazy. But our vision for Suspense has always been about much more than loading code — the goal is to extend support for Suspense so that eventually, the same declarative Suspense fallback can handle any asynchronous operation (loading code, data, images, etc).

和以前版本的 React 一樣鞍爱,您也可以使用 suspects 在客戶機上使用 React.lazy 進行代碼分割鹃觉。但是,我們對于懸念的愿景一直遠不止是加載代碼ーー我們的目標是擴展對懸念的支持睹逃,以便最終盗扇,同樣的聲明性懸念回退可以處理任何異步操作(加載代碼祷肯、數(shù)據(jù)、圖像等)疗隶。

Server Components is Still in Development 服務器組件仍在開發(fā)中

Server Components is an upcoming feature that allows developers to build apps that span the server and client, combining the rich interactivity of client-side apps with the improved performance of traditional server rendering. Server Components is not inherently coupled to Concurrent React, but it’s designed to work best with concurrent features like Suspense and streaming server rendering.

服務器組件是一個即將到來的功能佑笋,它允許開發(fā)人員構(gòu)建跨服務器和客戶端的應用程序,將客戶端應用程序的豐富交互性與傳統(tǒng)服務器渲染的改進性能結(jié)合起來斑鼻。服務器組件本質(zhì)上并不與并發(fā)反應耦合蒋纬,但是它被設(shè)計成能夠最好地工作于并發(fā)特性,比如懸念和媒體伺服器渲染坚弱。

Server Components is still experimental, but we expect to release an initial version in a minor 18.x release. In the meantime, we’re working with frameworks like Next.js, Hydrogen, and Remix to advance the proposal and get it ready for broad adoption.

服務器組件仍然處于試驗階段蜀备,但我們希望在一個較小的18.x 版本中發(fā)布初始版本。與此同時荒叶,我們正在與 Next.js碾阁、 Hydrogen 和 Remix 這樣的框架合作,以推進這一提議些楣,并為其廣泛應用做好準備脂凶。

What’s New in React 18 反應18的新發(fā)現(xiàn)

New Feature: Automatic Batching 新功能: 自動批處理

Batching is when React groups multiple state updates into a single re-render for better performance. Without automatic batching, we only batched updates inside React event handlers. Updates inside of promises, setTimeout, native event handlers, or any other event were not batched in React by default. With automatic batching, these updates will be batched automatically:

批處理是指 React 將多個狀態(tài)更新分組到單個重新呈現(xiàn)中,以獲得更好的性能愁茁。沒有自動批處理蚕钦,我們只能在 React 事件處理程序中批處理更新。在 React 默認情況下鹅很,promises嘶居、 setTimeout、本機事件處理程序或任何其他事件中的更新都不會批處理道宅。通過自動批處理食听,這些更新將自動批處理:

// Before: only React events were batched.
setTimeout(() => {
  setCount(c => c + 1);
  setFlag(f => !f);
  // React will render twice, once for each state update (no batching)
}, 1000);

// After: updates inside of timeouts, promises,
// native event handlers or any other event are batched.`
setTimeout(() => {
  setCount(c => c + 1);
  setFlag(f => !f);
  // React will only re-render once at the end (that's batching!)
}, 1000);

For more info, see this post for Automatic batching for fewer renders in React 18.

更多信息胸蛛,請看這篇文章自動批處理較少的渲染在反應18污茵。

New Feature: Transitions 新特性: 過渡

A transition is a new concept in React to distinguish between urgent and non-urgent updates.

轉(zhuǎn)換是 React 中區(qū)分緊急更新和非緊急更新的一個新概念。

  • Urgent updates 緊急更新 reflect direct interaction, like typing, clicking, pressing, and so on. 反映了直接的交互葬项,比如打字泞当、點擊、按壓等等
  • Transition updates 轉(zhuǎn)換更新 transition the UI from one view to another. 將 UI 從一個視圖轉(zhuǎn)換到另一個視圖

Urgent updates like typing, clicking, or pressing, need immediate response to match our intuitions about how physical objects behave. Otherwise they feel “wrong”. However, transitions are different because the user doesn’t expect to see every intermediate value on screen.

像打字民珍、點擊或按鍵這樣的緊急更新需要立即響應襟士,以匹配我們對物理對象行為的直覺。否則他們會覺得“錯了”嚷量。然而陋桂,轉(zhuǎn)場是不同的,因為用戶并不期望在屏幕上看到每一個中間值蝶溶。

For example, when you select a filter in a dropdown, you expect the filter button itself to respond immediately when you click. However, the actual results may transition separately. A small delay would be imperceptible and often expected. And if you change the filter again before the results are done rendering, you only care to see the latest results.

例如嗜历,當您在下拉菜單中選擇一個過濾器時宣渗,您希望過濾器按鈕本身在您單擊時立即響應。然而梨州,實際結(jié)果可能會單獨轉(zhuǎn)換痕囱。一個小小的延遲是察覺不到的,而且常常是可以預料到的暴匠。如果在渲染結(jié)果之前再次更改過濾器鞍恢,則只關(guān)心最新的結(jié)果。

Typically, for the best user experience, a single user input should result in both an urgent update and a non-urgent one. You can use startTransition API inside an input event to inform React which updates are urgent and which are “transitions”:

通常每窖,為了獲得最佳的用戶體驗帮掉,單個用戶輸入應該導致緊急更新和非緊急更新。您可以在輸入事件中使用 startTransition API 來通知 React 哪些更新是緊急的窒典,哪些是“轉(zhuǎn)換”:

import {startTransition} from 'react';

// Urgent: Show what was typed
setInputValue(input);

// Mark any state updates inside as transitions
startTransition(() => {
  // Transition: Show the results
  setSearchQuery(input);
});

Updates wrapped in startTransition are handled as non-urgent and will be interrupted if more urgent updates like clicks or key presses come in. If a transition gets interrupted by the user (for example, by typing multiple characters in a row), React will throw out the stale rendering work that wasn’t finished and render only the latest update.

包裝在 startTransition 中的更新將作為非緊急更新處理旭寿,如果進入更多緊急更新(如單擊或按鍵) ,更新將被中斷崇败。如果轉(zhuǎn)換被用戶打斷(例如盅称,在一行中鍵入多個字符) ,React 將拋出未完成的陳舊呈現(xiàn)工作后室,只呈現(xiàn)最新更新缩膝。

  • useTransition: a hook to start transitions, including a value to track the pending state. : 用于啟動轉(zhuǎn)換的鉤子,包括用于跟蹤掛起狀態(tài)的值
  • startTransition: a method to start transitions when the hook cannot be used. 當鉤子不能被使用時岸霹,一個開始轉(zhuǎn)換的方法

Transitions will opt in to concurrent rendering, which allows the update to be interrupted. If the content re-suspends, transitions also tell React to continue showing the current content while rendering the transition content in the background (see the Suspense RFC for more info).

轉(zhuǎn)換將選擇并發(fā)呈現(xiàn)疾层,這允許更新被中斷。如果內(nèi)容重新掛起贡避,轉(zhuǎn)場也會告訴 React 繼續(xù)顯示當前內(nèi)容痛黎,同時在背景中呈現(xiàn)轉(zhuǎn)場內(nèi)容(更多信息請參見暫停 RFC)。

See docs for transitions here.

點擊這里查看轉(zhuǎn)換文檔刮吧。

New Suspense Features 新的懸疑特色

Suspense lets you declaratively specify the loading state for a part of the component tree if it’s not yet ready to be displayed:

懸念可以讓你聲明性地指定組件樹中還沒有準備好顯示的部分的加載狀態(tài):

<Suspense fallback={<Spinner />}>
  <Comments />
</Suspense>

Suspense makes the “UI loading state” a first-class declarative concept in the React programming model. This lets us build higher-level features on top of it.

懸念使“ UI 加載狀態(tài)”成為 React 編程模型中的第一類聲明性概念湖饱。這讓我們可以在它的基礎(chǔ)上構(gòu)建更高級的特性。

We introduced a limited version of Suspense several years ago. However, the only supported use case was code splitting with React.lazy, and it wasn’t supported at all when rendering on the server.

幾年前我們推出了一個有限版本的懸念杀捻。但是井厌,唯一受支持的用例是與 React.lazy 進行代碼分割,而且在服務器上呈現(xiàn)時根本不支持這個用例致讥。

In React 18, we’ve added support for Suspense on the server and expanded its capabilities using concurrent rendering features.

在第18次反應中仅仆,我們在服務器上增加了對懸念的支持,并且使用并發(fā)渲染特性擴展了它的功能垢袱。

Suspense in React 18 works best when combined with the transition API. If you suspend during a transition, React will prevent already-visible content from being replaced by a fallback. Instead, React will delay the render until enough data has loaded to prevent a bad loading state.

懸念在反應18工程最好的時候結(jié)合了過渡 API墓拜。如果在轉(zhuǎn)換期間掛起,React 將防止已經(jīng)可見的內(nèi)容被回退替換请契。相反咳榜,React 將延遲渲染潘懊,直到加載了足夠的數(shù)據(jù)以防止出現(xiàn)錯誤的加載狀態(tài)。

For more, see the RFC for Suspense in React 18.

欲了解更多贿衍,請參見反應18懸念的 RFC授舟。

New Client and Server Rendering APIs 新的客戶端和服務器渲染 api

In this release we took the opportunity to redesign the APIs we expose for rendering on the client and server. These changes allow users to continue using the old APIs in React 17 mode while they upgrade to the new APIs in React 18.

在這個版本中祈搜,我們利用機會重新設(shè)計了為在客戶機和服務器上呈現(xiàn)而公開的 api蔫缸。這些改變允許用戶在 React 17模式下繼續(xù)使用舊的 api,同時在 React 18中升級到新的 api乡小。

React DOM Client 反應 DOM 客戶端

These new APIs are now exported from react-dom/client:

這些新的 api 現(xiàn)在從 react-dom/client 導出:

  • createRoot: New method to create a root to : 創(chuàng)建 root to 的新方法render or 或unmount. Use it instead of 擎淤。使用它而不是ReactDOM.render. New features in React 18 don’t work without it. . React 18中的新特性沒有它就不能工作
  • hydrateRoot: New method to hydrate a server rendered application. Use it instead of : 新方法水化服務器呈現(xiàn)的應用程序奢啥。使用它而不是ReactDOM.hydrate in conjunction with the new React DOM Server APIs. New features in React 18 don’t work without it. 與新的 React DOM Server api 一起使用。 React 18中的新特性離不開它

Both createRoot and hydrateRoot accept a new option called onRecoverableError in case you want to be notified when React recovers from errors during rendering or hydration for logging. By default, React will use reportError, or console.error in the older browsers.

和 hydrateRoot 都接受一個新的選項嘴拢,叫做 onRecoverableError桩盲,以防你想在 React recovered from errors during rendering 或 hydration for logging 時得到通知。默認情況下席吴,reportError 或 console.error 將在舊的瀏覽器中使用赌结。

See docs for React DOM Client here.

點擊這里查看 React DOM Client 的文檔。

React DOM Server 反應 DOM 服務器

These new APIs are now exported from react-dom/server and have full support for streaming Suspense on the server:

這些新的 api 現(xiàn)在從 react-dom/server 導出孝冒,并在服務器上完全支持流懸念:

  • renderToPipeableStream: for streaming in Node environments. : 用于 Node 環(huán)境中的流媒體
  • renderToReadableStream: for modern edge runtime environments, such as Deno and Cloudflare workers. : 用于現(xiàn)代邊緣運行時環(huán)境柬姚,如 Deno 和 Cloudflare workers

The existing renderToString method keeps working but is discouraged.

現(xiàn)有的 renderToString 方法繼續(xù)工作,但不提倡使用庄涡。

See docs for React DOM Server here.

點擊這里查看 React DOM Server 文檔量承。

New Strict Mode Behaviors 新的嚴格模式行為

In the future, we’d like to add a feature that allows React to add and remove sections of the UI while preserving state. For example, when a user tabs away from a screen and back, React should be able to immediately show the previous screen. To do this, React would unmount and remount trees using the same component state as before.

在未來,我們希望添加一個特性穴店,允許 React 添加和刪除 UI 的部分撕捍,同時保留狀態(tài)。例如泣洞,當用戶選項卡遠離屏幕并返回時忧风,React 應該能夠立即顯示前一個屏幕。為此斜棚,React 將使用與前面相同的組件狀態(tài)卸載和重新掛載樹阀蒂。

This feature will give React apps better performance out-of-the-box, but requires components to be resilient to effects being mounted and destroyed multiple times. Most effects will work without any changes, but some effects assume they are only mounted or destroyed once.

這一特性將使 React 應用程序具有更好的開箱即用性能,但需要組件能夠適應多次掛載和銷毀的效果弟蚀。大多數(shù)效果不需要任何改變就可以工作,但是有些效果假設(shè)它們只被安裝或者銷毀一次酗失。

To help surface these issues, React 18 introduces a new development-only check to Strict Mode. This new check will automatically unmount and remount every component, whenever a component mounts for the first time, restoring the previous state on the second mount.

為了幫助表面這些問題义钉,第18個反應引入了一個新的開發(fā)-只檢查嚴格模式。每當一個組件第一次掛載時规肴,這個新的檢查將自動卸載和重新掛載每個組件捶闸,恢復第二次掛載時以前的狀態(tài)夜畴。

Before this change, React would mount the component and create the effects:

在此更改之前,React 將掛載組件并創(chuàng)建效果:

* React mounts the component.
  * Layout effects are created.
  * Effects are created.

With Strict Mode in React 18, React will simulate unmounting and remounting the component in development mode:

使用反應18中的嚴格模式删壮,React 將模擬在開發(fā)模式下拆卸和重新安裝組件:

* React mounts the component.
  * Layout effects are created.
  * Effects are created.
* React simulates unmounting the component.
  * Layout effects are destroyed.
  * Effects are destroyed.
* React simulates mounting the component with the previous state.
  * Layout effects are created.
  * Effects are created.

See docs for ensuring resusable state here.

請參閱文檔以確碧盎妫可重復使用狀態(tài)。

New Hooks 新鉤子

useId 有用的 id

useId is a new hook for generating unique IDs on both the client and server, while avoiding hydration mismatches. It is primarily useful for component libraries integrating with accessibility APIs that require unique IDs. This solves an issue that already exists in React 17 and below, but it’s even more important in React 18 because of how the new streaming server renderer delivers HTML out-of-order. See docs here.

useId 是一個新的鉤子央碟,用于在客戶機和服務器上生成唯一的 id税灌,同時避免水合不匹配。它主要用于組件庫與需要唯一 id 的可訪問性 api 集成亿虽。這解決了一個在 React 17及以下版本中已經(jīng)存在的問題菱涤,但是在 React 18中這個問題更加重要,因為新的媒體伺服器渲染器是如何無序地傳遞 HTML 的洛勉。請看這里的文件粘秆。

useTransition 使用轉(zhuǎn)換

useTransition and startTransition let you mark some state updates as not urgent. Other state updates are considered urgent by default. React will allow urgent state updates (for example, updating a text input) to interrupt non-urgent state updates (for example, rendering a list of search results). See docs here

Usevance 和 startTransition 允許您將某些狀態(tài)更新標記為非緊急狀態(tài)。默認情況下收毫,其他狀態(tài)更新被認為是緊急的攻走。響應將允許緊急狀態(tài)更新(例如,更新文本輸入)中斷非緊急狀態(tài)更新(例如此再,呈現(xiàn)搜索結(jié)果列表)陋气。請看這里的文件

useDeferredValue 使用 deferredvalue

useDeferredValue lets you defer re-rendering a non-urgent part of the tree. It is similar to debouncing, but has a few advantages compared to it. There is no fixed time delay, so React will attempt the deferred render right after the first render is reflected on the screen. The deferred render is interruptible and doesn’t block user input. See docs here.

useDeferredValue 允許您推遲重新呈現(xiàn)樹的非緊急部分。它類似于債務減記引润,但與債務減記相比有一些優(yōu)點巩趁。沒有固定的時間延遲,所以在第一次渲染反映在屏幕上之后淳附,React 會嘗試延遲渲染议慰。延遲渲染是可中斷的,不會阻塞用戶輸入奴曙。請看這里的文件别凹。

useSyncExternalStore

useSyncExternalStore is a new hook that allows external stores to support concurrent reads by forcing updates to the store to be synchronous. It removes the need for useEffect when implementing subscriptions to external data sources, and is recommended for any library that integrates with state external to React. See docs here.

useSyncExternalStore 是一個新的掛鉤,它允許外部存儲通過強制存儲的更新為同步更新來支持并發(fā)讀取洽糟。在實現(xiàn)對外部數(shù)據(jù)源的訂閱時炉菲,它消除了對 useEffect 的需要,并且建議任何與狀態(tài)外部集成到 React 的庫使用它坤溃。請看這里的文件拍霜。

Note

注意

useSyncExternalStore is intended to be used by libraries, not application code.

useSyncExternalStore 用于庫,而不是應用程序代碼薪介。

useInsertionEffect 插入效果

useInsertionEffect is a new hook that allows CSS-in-JS libraries to address performance issues of injecting styles in render. Unless you’ve already built a CSS-in-JS library we don’t expect you to ever use this. This hook will run after the DOM is mutated, but before layout effects read the new layout. This solves an issue that already exists in React 17 and below, but is even more important in React 18 because React yields to the browser during concurrent rendering, giving it a chance to recalculate layout. See docs here.

useInsertionEffect 是一個新的鉤子祠饺,它允許 CSS-in-JS 庫解決渲染中注入樣式的性能問題。除非您已經(jīng)構(gòu)建了一個 CSS-in-JS 庫汁政,否則我們不希望您使用它道偷。這個鉤子將在 DOM 變異后運行缀旁,但是在布局效果之前讀取新的布局。這解決了一個在 React 17及以下版本中已經(jīng)存在的問題勺鸦,但在 React 18中更為重要并巍,因為 React 在并發(fā)呈現(xiàn)過程中向瀏覽器屈服,給了瀏覽器重新計算布局的機會换途。請看這里的文件懊渡。

Note

注意

useInsertionEffect is intended to be used by libraries, not application code.

Usedinsertioneffect 適用于庫,而不是應用程序代碼怀跛。

?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
  • 序言:七十年代末距贷,一起剝皮案震驚了整個濱河市,隨后出現(xiàn)的幾起案子吻谋,更是在濱河造成了極大的恐慌忠蝗,老刑警劉巖,帶你破解...
    沈念sama閱讀 206,839評論 6 482
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件漓拾,死亡現(xiàn)場離奇詭異阁最,居然都是意外死亡,警方通過查閱死者的電腦和手機骇两,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 88,543評論 2 382
  • 文/潘曉璐 我一進店門速种,熙熙樓的掌柜王于貴愁眉苦臉地迎上來,“玉大人低千,你說我怎么就攤上這事配阵。” “怎么了示血?”我有些...
    開封第一講書人閱讀 153,116評論 0 344
  • 文/不壞的土叔 我叫張陵棋傍,是天一觀的道長。 經(jīng)常有香客問我难审,道長瘫拣,這世上最難降的妖魔是什么? 我笑而不...
    開封第一講書人閱讀 55,371評論 1 279
  • 正文 為了忘掉前任告喊,我火速辦了婚禮麸拄,結(jié)果婚禮上,老公的妹妹穿的比我還像新娘黔姜。我一直安慰自己拢切,他們只是感情好,可當我...
    茶點故事閱讀 64,384評論 5 374
  • 文/花漫 我一把揭開白布地淀。 她就那樣靜靜地躺著失球,像睡著了一般。 火紅的嫁衣襯著肌膚如雪帮毁。 梳的紋絲不亂的頭發(fā)上实苞,一...
    開封第一講書人閱讀 49,111評論 1 285
  • 那天,我揣著相機與錄音烈疚,去河邊找鬼黔牵。 笑死,一個胖子當著我的面吹牛爷肝,可吹牛的內(nèi)容都是我干的猾浦。 我是一名探鬼主播,決...
    沈念sama閱讀 38,416評論 3 400
  • 文/蒼蘭香墨 我猛地睜開眼灯抛,長吁一口氣:“原來是場噩夢啊……” “哼金赦!你這毒婦竟也來了?” 一聲冷哼從身側(cè)響起对嚼,我...
    開封第一講書人閱讀 37,053評論 0 259
  • 序言:老撾萬榮一對情侶失蹤夹抗,失蹤者是張志新(化名)和其女友劉穎,沒想到半個月后纵竖,有當?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體漠烧,經(jīng)...
    沈念sama閱讀 43,558評論 1 300
  • 正文 獨居荒郊野嶺守林人離奇死亡,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點故事閱讀 36,007評論 2 325
  • 正文 我和宋清朗相戀三年靡砌,在試婚紗的時候發(fā)現(xiàn)自己被綠了已脓。 大學時的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片。...
    茶點故事閱讀 38,117評論 1 334
  • 序言:一個原本活蹦亂跳的男人離奇死亡通殃,死狀恐怖度液,靈堂內(nèi)的尸體忽然破棺而出,到底是詐尸還是另有隱情画舌,我是刑警寧澤堕担,帶...
    沈念sama閱讀 33,756評論 4 324
  • 正文 年R本政府宣布,位于F島的核電站骗炉,受9級特大地震影響照宝,放射性物質(zhì)發(fā)生泄漏。R本人自食惡果不足惜句葵,卻給世界環(huán)境...
    茶點故事閱讀 39,324評論 3 307
  • 文/蒙蒙 一厕鹃、第九天 我趴在偏房一處隱蔽的房頂上張望。 院中可真熱鬧乍丈,春花似錦剂碴、人聲如沸。這莊子的主人今日做“春日...
    開封第一講書人閱讀 30,315評論 0 19
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽。三九已至,卻和暖如春催训,著一層夾襖步出監(jiān)牢的瞬間洽议,已是汗流浹背。 一陣腳步聲響...
    開封第一講書人閱讀 31,539評論 1 262
  • 我被黑心中介騙來泰國打工漫拭, 沒想到剛下飛機就差點兒被人妖公主榨干…… 1. 我叫王不留亚兄,地道東北人。 一個月前我還...
    沈念sama閱讀 45,578評論 2 355
  • 正文 我出身青樓采驻,卻偏偏與公主長得像审胚,于是被迫代替她去往敵國和親。 傳聞我的和親對象是個殘疾皇子礼旅,可洞房花燭夜當晚...
    茶點故事閱讀 42,877評論 2 345

推薦閱讀更多精彩內(nèi)容