首页  >  文章  >  web前端  >  React 综合指南

React 综合指南

WBOY
WBOY原创
2024-08-07 01:45:43350浏览

React  A Comprehensive Guide

React 19 来了! ?在本文中,我们将探索 React 19 中的新功能和改进。让我们开始吧!

React 19 的新增功能

React 19 是 React 团队的最新主要版本,具有多项突破性功能和增强功能,旨在使开发过程更加高效,并使生成的应用程序更快、更强大。该版本继续建立在其前身奠定的坚实基础上,对核心框架进行了重大更新。在这篇博客中,我们将探索 React 19 的主要功能,包括新的 React 编译器、服务器组件和服务器操作、新的钩子和 API 等等!

反应编译器

React 19 中最令人兴奋的功能之一是新的 React 编译器,也称为 React Fizz。该编译器旨在通过生成高效的 JavaScript 代码来优化 React 应用程序的性能。 React 编译器将您的 JSX 和 JavaScript 代码转换为高度优化的 JavaScript,可以更快地执行、更好的内存使用和更少的开销。这仍处于实验模式,但它是一个很有前途的功能,可能会改变 React 开发人员的游戏规则。它使用纯 JavaScript,并理解 React 规则,因此您无需重写任何代码即可使用它。

编译器做什么?

为了优化应用程序,React Compiler会自动记忆组件和钩子,并优化渲染过程。这意味着React只会重新渲染实际发生变化的组件,而不是重新渲染整个组件树。这可以显着提高性能,特别是对于大型复杂的应用程序。

如果您的代码库已经被很好地记住,您可能不会期望看到编译器的重大性能改进。然而,在实践中,手动记住导致性能问题的正确依赖关系是很棘手的。编译器可以帮助你。

编译器假设什么?

React 编译器假设您的代码:

  • 是有效的、语义的 JavaScript
  • 在访问可空/可选值和属性之前测试它们是否已定义(例如,如果使用 TypeScript,则通过启用 strictNullChecks),即 if (object.nullableProperty) { object.nullableProperty.foo } 或使用可选链对象。 nullableProperty?.foo
  • 遵循React规则

React Compiler 可以静态验证 React 的许多规则,并在检测到错误时安全地跳过编译。

服务器组件和服务器操作

服务器组件可以在构建时运行以从文件系统读取或获取静态内容,因此不需要 Web 服务器。例如,您可能想从内容管理系统读取静态数据。

没有服务器的服务器组件

如果没有服务器组件,在客户端获取静态数据很常见,效果如下:

// bundle.js
import marked from 'marked'; // 35.9K (11.2K gzipped)
import sanitizeHtml from 'sanitize-html'; // 206K (63.3K gzipped)

function Page({page}) {
  const [content, setContent] = useState('');
  // NOTE: loads *after* first page render.
  useEffect(() => {
    fetch(`/api/content/${page}`).then((data) => {
      setContent(data.content);
    });
  }, [page]);

  return <div>{sanitizeHtml(marked(content))}</div>;
}

使用服务器组件,您可以在构建时获取静态数据:

import marked from 'marked'; // Not included in bundle
import sanitizeHtml from 'sanitize-html'; // Not included in bundle

async function Page({page}) {
  // NOTE: loads *during* render, when the app is built.
  const content = await file.readFile(`${page}.md`);

  return <div>{sanitizeHtml(marked(content))}</div>;
}

渲染的输出可以被缓存并静态提供,因此服务器不需要运行任何 JavaScript。这对于性能来说是一个巨大的胜利,尤其是在移动设备上。当应用程序加载时,它可以立即显示内容,无需等待网络请求。

带有服务器的服务器组件

服务器组件也可以在服务器上运行。这对于获取非静态数据非常有用,例如特定于用户的数据或经常更改的数据。例如,您可能希望从数据库中获取特定于用户的数据,这通常是通过使用 useEffect 挂钩来实现的:

// bundle.js
function Note({id}) {
  const [note, setNote] = useState('');
  // NOTE: loads *after* first render.
  useEffect(() => {
    fetch(`/api/notes/${id}`).then(data => {
      setNote(data.note);
    });
  }, [id]);

  return (
    <div>
      <Author id={note.authorId} />
      <p>{note}</p>
    </div>
  );
}

function Author({id}) {
  const [author, setAuthor] = useState('');
  // NOTE: loads *after* Note renders.
  // Causing an expensive client-server waterfall.
  useEffect(() => {
    fetch(`/api/authors/${id}`).then(data => {
      setAuthor(data.author);
    });
  }, [id]);

  return <span>By: {author.name}</span>;
}

使用服务器组件,您可以读取数据并在组件中渲染它:

import db from './database';

async function Note({id}) {
  // NOTE: loads *during* render.
  const note = await db.notes.get(id);
  return (
    <div>
      <Author id={note.authorId} />
      <p>{note}</p>
    </div>
  );
}

async function Author({id}) {
  // NOTE: loads *after* Note,
  // but is fast if data is co-located.
  const author = await db.authors.get(id);
  return <span>By: {author.name}</span>;
}

服务器组件可以通过从服务器重新获取它们来动态化,它们可以在服务器上访问数据并再次渲染。这种新的应用程序架构结合了以服务器为中心的多页面应用程序的简单“请求/响应”心理模型与以客户端为中心的单页应用程序的无缝交互性,为您提供两全其美的优势。

服务器操作

当使用“use server”指令定义服务器操作时,您的框架将自动创建对服务器函数的引用,并将该引用传递给客户端组件。当客户端调用该函数时,React 会向服务器发送请求来执行该函数,并返回结果。

服务器操作可以在服务器组件中创建并作为道具传递给客户端组件,也可以在客户端组件中导入和使用。

Creating a Server Action from a Server Component:

// Server Component
import Button from './Button';

function EmptyNote () {
  async function createNoteAction() {
    // Server Action
    'use server';

    await db.notes.create();
  }

  return <Button onClick={createNoteAction}/>;
}

When React renders the EmptyNote Server Component, it will create a reference to the createNoteAction function, and pass that reference to the Button Client Component. When the button is clicked, React will send a request to the server to execute the createNoteAction function with the reference provided:

"use client";

export default function Button({onClick}) { 
  console.log(onClick); 
  return <button onClick={onClick}>Create Empty Note</button>
}

Importing and using a Server Action in a Client Component:

Client Components can import Server Actions from files that use the "use server" directive:

"use server";

export async function createNoteAction() {
  await db.notes.create();
}

When the bundler builds the EmptyNote Client Component, it will create a reference to the createNoteAction function in the bundle. When the button is clicked, React will send a request to the server to execute the createNoteAction function using the reference provided:

"use client";
import {createNoteAction} from './actions';

function EmptyNote() {
  console.log(createNoteAction);
  // {$$typeof: Symbol.for("react.server.reference"), $$id: 'createNoteAction'}
  <button onClick={createNoteAction} />
}

New Hooks and APIs

Besides the React Compiler and Server Components, React 19 introduces several new hooks and APIs that make it easier to build complex applications.

useOptimistic

The useOptimistic hook allows you to update the UI optimistically before the server responds. This can make your application feel more responsive and reduce the perceived latency. The hook takes a callback function that performs the optimistic update, and an optional configuration object that specifies the server request to send after the optimistic update.

useFormStatus

The useFormStatus hook allows you to track the status of a form, such as whether it is pristine, dirty, valid, or invalid. This can be useful for displaying feedback to the user, such as error messages or success messages.

useFormState

The useFormState hook allows you to manage the state of a form, such as the values of the form fields and the validity of the form. This can be useful for building complex forms with dynamic validation logic.

This hook requires two arguments: the initial form state and a validation function. The validation function takes the form state as input and returns an object with the validity of each form field.

The new use API

React 19 introduces a new use API that is a versatile way to read values from resources like Promises or context. The use API is similar to the useEffect hook, but it doesn't take a callback function. Instead, it returns the value of the resource, and re-renders the component when the value changes.

const value = use(resource);

Example:

import { use } from 'react';

function MessageComponent({ messagePromise }) {
  const message = use(messagePromise);
  const theme = use(ThemeContext);
  // ...

Conclusion - Should You Upgrade to React 19?

React 19 is a major release that introduces several groundbreaking features and enhancements to the core framework. The new React Compiler, Server Components, and Server Actions are designed to make the development process more efficient and the resulting applications faster and more powerful. The new hooks and APIs make it easier to build complex applications and improve the user experience. If you're already using React, upgrading to React 19 is definitely worth considering.

But at the same time it's important to note that React 19 is still in experimental mode, and some features may change before the final release. It's recommended to test your application with React 19 in a non-production environment before upgrading. If you're starting a new project, React 19 is a great choice, as it provides a solid foundation for building modern web applications.

以上是React 综合指南的详细内容。更多信息请关注PHP中文网其他相关文章!

声明:
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn