搜尋
首頁web前端js教程React 綜合指南

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}"></author>
      <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}"></author>
      <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}/">;
}
</button>

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}"></button>
}

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
JavaScript引擎:比較實施JavaScript引擎:比較實施Apr 13, 2025 am 12:05 AM

不同JavaScript引擎在解析和執行JavaScript代碼時,效果會有所不同,因為每個引擎的實現原理和優化策略各有差異。 1.詞法分析:將源碼轉換為詞法單元。 2.語法分析:生成抽象語法樹。 3.優化和編譯:通過JIT編譯器生成機器碼。 4.執行:運行機器碼。 V8引擎通過即時編譯和隱藏類優化,SpiderMonkey使用類型推斷系統,導致在相同代碼上的性能表現不同。

超越瀏覽器:現實世界中的JavaScript超越瀏覽器:現實世界中的JavaScriptApr 12, 2025 am 12:06 AM

JavaScript在現實世界中的應用包括服務器端編程、移動應用開發和物聯網控制:1.通過Node.js實現服務器端編程,適用於高並發請求處理。 2.通過ReactNative進行移動應用開發,支持跨平台部署。 3.通過Johnny-Five庫用於物聯網設備控制,適用於硬件交互。

使用Next.js(後端集成)構建多租戶SaaS應用程序使用Next.js(後端集成)構建多租戶SaaS應用程序Apr 11, 2025 am 08:23 AM

我使用您的日常技術工具構建了功能性的多租戶SaaS應用程序(一個Edtech應用程序),您可以做同樣的事情。 首先,什麼是多租戶SaaS應用程序? 多租戶SaaS應用程序可讓您從唱歌中為多個客戶提供服務

如何使用Next.js(前端集成)構建多租戶SaaS應用程序如何使用Next.js(前端集成)構建多租戶SaaS應用程序Apr 11, 2025 am 08:22 AM

本文展示了與許可證確保的後端的前端集成,並使用Next.js構建功能性Edtech SaaS應用程序。 前端獲取用戶權限以控制UI的可見性並確保API要求遵守角色庫

JavaScript:探索網絡語言的多功能性JavaScript:探索網絡語言的多功能性Apr 11, 2025 am 12:01 AM

JavaScript是現代Web開發的核心語言,因其多樣性和靈活性而廣泛應用。 1)前端開發:通過DOM操作和現代框架(如React、Vue.js、Angular)構建動態網頁和單頁面應用。 2)服務器端開發:Node.js利用非阻塞I/O模型處理高並發和實時應用。 3)移動和桌面應用開發:通過ReactNative和Electron實現跨平台開發,提高開發效率。

JavaScript的演變:當前的趨勢和未來前景JavaScript的演變:當前的趨勢和未來前景Apr 10, 2025 am 09:33 AM

JavaScript的最新趨勢包括TypeScript的崛起、現代框架和庫的流行以及WebAssembly的應用。未來前景涵蓋更強大的類型系統、服務器端JavaScript的發展、人工智能和機器學習的擴展以及物聯網和邊緣計算的潛力。

神秘的JavaScript:它的作用以及為什麼重要神秘的JavaScript:它的作用以及為什麼重要Apr 09, 2025 am 12:07 AM

JavaScript是現代Web開發的基石,它的主要功能包括事件驅動編程、動態內容生成和異步編程。 1)事件驅動編程允許網頁根據用戶操作動態變化。 2)動態內容生成使得頁面內容可以根據條件調整。 3)異步編程確保用戶界面不被阻塞。 JavaScript廣泛應用於網頁交互、單頁面應用和服務器端開發,極大地提升了用戶體驗和跨平台開發的靈活性。

Python還是JavaScript更好?Python還是JavaScript更好?Apr 06, 2025 am 12:14 AM

Python更适合数据科学和机器学习,JavaScript更适合前端和全栈开发。1.Python以简洁语法和丰富库生态著称,适用于数据分析和Web开发。2.JavaScript是前端开发核心,Node.js支持服务器端编程,适用于全栈开发。

See all articles

熱AI工具

Undresser.AI Undress

Undresser.AI Undress

人工智慧驅動的應用程序,用於創建逼真的裸體照片

AI Clothes Remover

AI Clothes Remover

用於從照片中去除衣服的線上人工智慧工具。

Undress AI Tool

Undress AI Tool

免費脫衣圖片

Clothoff.io

Clothoff.io

AI脫衣器

AI Hentai Generator

AI Hentai Generator

免費產生 AI 無盡。

熱門文章

R.E.P.O.能量晶體解釋及其做什麼(黃色晶體)
3 週前By尊渡假赌尊渡假赌尊渡假赌
R.E.P.O.最佳圖形設置
3 週前By尊渡假赌尊渡假赌尊渡假赌
R.E.P.O.如果您聽不到任何人,如何修復音頻
3 週前By尊渡假赌尊渡假赌尊渡假赌
WWE 2K25:如何解鎖Myrise中的所有內容
4 週前By尊渡假赌尊渡假赌尊渡假赌

熱工具

VSCode Windows 64位元 下載

VSCode Windows 64位元 下載

微軟推出的免費、功能強大的一款IDE編輯器

SublimeText3 Linux新版

SublimeText3 Linux新版

SublimeText3 Linux最新版

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

強大的PHP整合開發環境

SublimeText3 英文版

SublimeText3 英文版

推薦:為Win版本,支援程式碼提示!

Atom編輯器mac版下載

Atom編輯器mac版下載

最受歡迎的的開源編輯器