vlambda博客
学习文章列表

React18的Releases都写了什么!

清明小长假一晃过去了,我也来追更一下,虽然有点不及时哈,大家抱歉哈。2022年3月29日React18正式发布了。我们来看一下18的release日志,篇幅还挺长的。

Below is a list of all new features, APIs, deprecations, and breaking changes. Read React 18 release post and React 18 upgrade guide for more information.

以下列表列举了所有新特性、API、弃用和重大更改

New Features 新特性

React

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.

useId用于在客户端和服务端生成唯一ID的新的hook,避免“注水”(React在客户端渲染,生成随机id,这一步叫hydrate)客户端、服务端生成的id不匹配。对于需要唯一ID的可访问性API集成的组件库来说非常有用。这解决了React 17及以下版本中已经存在的一个问题,但在React 18中更为重要,因为新的流媒体服务器渲染器如何无序地交付HTML。

startTransition and useTransition 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).

startTransitionuseTransition允许标记一些不紧急的状态更新。其它状态的更新默认是紧急更新。React将允许紧急状态更新(例如,更新文本输入)中断非紧急状态更新(例如,呈现搜索结果列表)。

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.

useDeferredValue允许延迟重新渲染树的非紧急部分。和debouncing类似,但是优于debouncing。没有固定的延迟时间,因此React将在第一次渲染反映在屏幕上后立即开始延迟渲染。延迟渲染是可中断的,不会阻止用户输入。

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.

useSyncExternalStore是一个新的hook通过强制同步更新防止在并发模式下任务中断后第三方 store 被修改。在实现对外部数据源的订阅时,它不再需要useEffect,是引用第三方状态管理库的推荐做法。

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.

useInsertionEffect是一个新的hook对现有的专为 React 设计的 css-in-js 库有着很大的作用可以动态生成新规则与<style>标签一起插入到文档中。除非您已经在JS库中构建了CSS,否则我们不希望您使用它。这个hook运行在DOM引用改变之后,有新布局效果之前。满足在所有 DOM 生成前插入并且不访问 DOM。这解决了在 React 17及以下版本中已经存在的一个问题,在 React 18中更为重要,因为发渲染期间React 会在浏览器环境中暂停执行,让浏览器重新计算布局。

React DOM Client

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

从react dom/client导出新的API:

createRoot: New method to create a root to render or unmount. Use it instead of ReactDOM.render. New features in React 18 don't work without it

createRoot: 新方法可以创建root渲染或者移除。用来代替ReactDOM.render。支持 React 18 中支持的所有新特性。

hydrateRoot: New method to hydrate a server rendered application. Use it instead of ReactDOM.hydrate in conjunction with the new React DOM Server APIs. New features in React 18 don't work without it.

hydrateRoot:新方法可以“注水”服务端渲染应用。用来代替ReactDOM.hydrate与新的 React DOM Server API 一起使用。

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.

createRoot和hydrateRoot都接收新的入参onRecoverableErro是为了能够记录/报告React中可能发生的 "可恢复的错误",特别是在SSR和CSR之间存在一些不适配的交融过程中。默认,React使用reportError或者console.error支持旧的浏览器。

React DOM Server

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

从react dom/server导出新的API完全支持服务端的流式Suspense。
  • renderToPipeableStream: for streaming in Node environments.

  • renderToReadableStream: for modern edge runtime environments, such as Deno and Cloudflare workers.

  • renderToPipeableStream: 在Node环境中支持流。

  • renderToReadableStream: 支持现代的运行时环境,例如Deno和 Cloudflare workers。

The existing renderToString method keeps working but is discouraged.

现有的renderToString方法仍然有用但不鼓励使用。

Deprecations

  • react-dom: ReactDOM.render has been deprecated. Using it will warn and run your app in React 17 mode.

  • react-dom: ReactDOM.hydrate has been deprecated. Using it will warn and run your app in React 17 mode.

  • react-dom: ReactDOM.unmountComponentAtNode has been deprecated.

  • react-dom: ReactDOM.renderSubtreeIntoContainer has been deprecated.

  • react-dom/server: ReactDOMServer.renderToNodeStream has been deprecated.

以上的API已经废弃。

Breaking Changes

React

Automatic batching: This release introduces a performance improvement that changes to the way React batches updates to do more batching automatically. See Automatic batching for fewer renders in React 18 for more info. In the rare case that you need to opt out, wrap the state update in flushSync.

自动批处理:此版本引入了一项性能改进,会尝试将同一上下文中触发的更新自动合并为一个更新。自动批处理在React18会减少更新流程调用次数。在极少数情况下你需要撤退,使用flushSync方法来包裹需要进行的操作。

Stricter Strict Mode: In the future, React will provide a feature that lets components preserve state between unmounts. To prepare for it, React 18 introduces a new development-only check to Strict Mode. React will automatically unmount and remount every component, whenever a component mounts for the first time, restoring the previous state on the second mount. If this breaks your app, consider removing Strict Mode until you can fix the components to be resilient to remounting with existing state.

更严格的严格模式:在未来,React将提供一个功能,允许组件在卸载之间保持状态。为了做好准备,React 18引入了一种新的仅限开发的严格检查模式。每当组件第一次装载时,React将自动卸载和重新装载每个组件,并在第二次装载时恢复以前的状态。如果这中断你的应用程序,考虑移除严格的模式,直到你可以修复组件保持弹性以恢复现有的状态。

Consistent useEffect timing: React now always synchronously flushes effect functions if the update was triggered during a discrete user input event such as a click or a keydown event. Previously, the behavior wasn't always predictable or consistent.

一致的useEffect时机:在一个离散的用户输入事件例如点击或者键盘事件触发更新的时候,React现在一直是同步地刷新effect函数。之前,这种行为不是可以预测或者一致的。

Stricter hydration errors: Hydration mismatches due to missing or extra text content are now treated like errors instead of warnings. React will no longer attempt to "patch up" individual nodes by inserting or deleting a node on the client in an attempt to match the server markup, and will revert to client rendering up to the closest <Suspense> boundary in the tree. This ensures the hydrated tree is consistent and avoids potential privacy and security holes that can be caused by hydration mismatches.

更严格的“注水”错误:由于缺少或额外的文本内容而导致的不匹配现在被视为错误,而不是警告。React将不再尝试通过插入或删除客户端上的节点来“修补”单个节点,来匹配服务器标记,并将在树中最近的<suspend>边界恢复客户端渲染。这确保了“注水”过程中树的一致性,避免因“注水”过程错误而引起的潜在隐私和安全漏洞。

Suspense trees are always consistent: If a component suspends before it's fully added to the tree, React will not add it to the tree in an incomplete state or fire its effects. Instead, React will throw away the new tree completely, wait for the asynchronous operation to finish, and then retry rendering again from scratch. React will render the retry attempt concurrently, and without blocking the browser.

Suspense树保持一致性:如果组件在完全添加到树之前挂起,React将不会在未完成state下将其添加到树中,也不会激发effects。相反,React将会完全地抛弃这个树,等待异步操作完成,然后从头开始重试渲染。React将并发地重新尝试render且不会阻塞浏览器。

Layout Effects with Suspense: When a tree re-suspends and reverts to a fallback, React will now clean up layout effects, and then re-create them when the content inside the boundary is shown again. This fixes an issue which prevented component libraries from correctly measuring layout when used with Suspense.

Suspense布局Effects:当树重新挂起并转换为回退时,React将清除布局effects,然后在再次显示边界内的内容时重新创建布局effects。这解决当与Suspense一起使用时,组件库无法正确测量布局的问题。

New JS Environment Requirements: React now depends on modern browsers features including Promise, Symbol, and Object.assign. If you support older browsers and devices such as Internet Explorer which do not provide modern browser features natively or have non-compliant implementations, consider including a global polyfill in your bundled application.

新的JS环境要求:React依赖于现代浏览器的功能,包括Promise、Symbol和Object.assign。支持旧的浏览器和设备(如Internet Explorer),它不支持现代浏览器的特性或有不兼容的问题,那么建议在应用程序中添加全局的polyfill。

Notable Changes

React

Components can now render undefined: React no longer throws if you return undefined from a component. This makes the allowed component return values consistent with values that are allowed in the middle of a component tree. We suggest to use a linter to prevent mistakes like forgetting a return statement before JSX

组件可以渲染undefined:当组件返回undefined的时候,React不再抛错。这使得组件返回值和组件树中间态返回值保持一致。建议使用linter来防止出现错误,比如在JSX之前忘记了return语句。

In tests, act warnings are now opt-in: If you're running end-to-end tests, the act warnings are unnecessary. We've introduced an opt-in mechanism so you can enable them only for unit tests where they are useful and beneficial.

在测试中,可以选择加入act警告如果运行端到端测试,则不需要act警告。我们引入了一种可选机制,你可以在单元测试中开启,act警告在单元测试中十分有用。

No warning about setState on unmounted components: Previously, React warned about memory leaks when you call setState on an unmounted component. This warning was added for subscriptions, but people primarily run into it in scenarios where setting state is fine, and workarounds make the code worse. We've removed this warning.

未安装组件上没有setState的警告:之前,React在对未安装的组件调用setState时会警告内存泄漏。这个警告是为订阅添加的,但人们主要运行在state设置良好的情况下,而消除警告会使代码变得更糟。我们已经移除了这个警告。

No suppression of console logs: When you use Strict Mode, React renders each component twice to help you find unexpected side effects. In React 17, we've suppressed console logs for one of the two renders to make the logs easier to read. In response to community feedback about this being confusing, we've removed the suppression. Instead, if you have React DevTools installed, the second log's renders will be displayed in grey, and there will be an option (off by default) to suppress them completely.

不删除console日志:在严格模式下,每一个组件React会渲染两次来帮助找到超出预期的副作用。在React17,我们删除了两次渲染中的一条日志,以使日志更易于阅读。为了回应社区对这个的反馈,我们取消了删除。取而代之,在安装了React DevTools的情况下,第二个渲染的日志会以灰色显示,并且会有一个选项(默认情况下关闭)来控制展示与否。

Improved memory usage: React now cleans up more internal fields on unmount, making the impact from unfixed memory leaks that may exist in your application code less severe.

提高内存使用率:React会在卸载的时候清除更多的内部字段,降低应用程序代码中可能存在的未修复内存泄漏的影响。

React DOM Server

renderToString: Will no longer error when suspending on the server. Instead, it will emit the fallback HTML for the closest <Suspense> boundary and then retry rendering the same content on the client. It is still recommended that you switch to a streaming API like renderToPipeableStream or renderToReadableStream instead.
renderToString:在服务端挂起不再会报错。取而代之在最近的<Suspense>边界会在HTML中emit回退然后尝试在客户端渲染相同的内容。建议您改用renderToPipeableStream或renderToReadableStream等流式API。
renderToStaticMarkup: Will no longer error when suspending on the server. Instead, it will emit the fallback HTML for the closest <Suspense> boundary and retry rendering on the client.
renderToStaticMarkup:在服务端挂起不再会报错。取而代之在最近的<Suspense>边界会在HTML中emit回退然后尝试在客户端渲染相同的内容。

All Changes

https://github.com/facebook/react/releases