React 綜合指南
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中文網其他相關文章!

熱AI工具

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

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

Undress AI Tool
免費脫衣圖片

Clothoff.io
AI脫衣器

Video Face Swap
使用我們完全免費的人工智慧換臉工具,輕鬆在任何影片中換臉!

熱門文章

熱工具

記事本++7.3.1
好用且免費的程式碼編輯器

SublimeText3漢化版
中文版,非常好用

禪工作室 13.0.1
強大的PHP整合開發環境

Dreamweaver CS6
視覺化網頁開發工具

SublimeText3 Mac版
神級程式碼編輯軟體(SublimeText3)

Python更適合初學者,學習曲線平緩,語法簡潔;JavaScript適合前端開發,學習曲線較陡,語法靈活。 1.Python語法直觀,適用於數據科學和後端開發。 2.JavaScript靈活,廣泛用於前端和服務器端編程。

JavaScript在Web開發中的主要用途包括客戶端交互、表單驗證和異步通信。 1)通過DOM操作實現動態內容更新和用戶交互;2)在用戶提交數據前進行客戶端驗證,提高用戶體驗;3)通過AJAX技術實現與服務器的無刷新通信。

JavaScript在現實世界中的應用包括前端和後端開發。 1)通過構建TODO列表應用展示前端應用,涉及DOM操作和事件處理。 2)通過Node.js和Express構建RESTfulAPI展示後端應用。

理解JavaScript引擎內部工作原理對開發者重要,因為它能幫助編寫更高效的代碼並理解性能瓶頸和優化策略。 1)引擎的工作流程包括解析、編譯和執行三個階段;2)執行過程中,引擎會進行動態優化,如內聯緩存和隱藏類;3)最佳實踐包括避免全局變量、優化循環、使用const和let,以及避免過度使用閉包。

Python和JavaScript在社區、庫和資源方面的對比各有優劣。 1)Python社區友好,適合初學者,但前端開發資源不如JavaScript豐富。 2)Python在數據科學和機器學習庫方面強大,JavaScript則在前端開發庫和框架上更勝一籌。 3)兩者的學習資源都豐富,但Python適合從官方文檔開始,JavaScript則以MDNWebDocs為佳。選擇應基於項目需求和個人興趣。

Python和JavaScript在開發環境上的選擇都很重要。 1)Python的開發環境包括PyCharm、JupyterNotebook和Anaconda,適合數據科學和快速原型開發。 2)JavaScript的開發環境包括Node.js、VSCode和Webpack,適用於前端和後端開發。根據項目需求選擇合適的工具可以提高開發效率和項目成功率。

C和C 在JavaScript引擎中扮演了至关重要的角色,主要用于实现解释器和JIT编译器。1)C 用于解析JavaScript源码并生成抽象语法树。2)C 负责生成和执行字节码。3)C 实现JIT编译器,在运行时优化和编译热点代码,显著提高JavaScript的执行效率。

JavaScript在網站、移動應用、桌面應用和服務器端編程中均有廣泛應用。 1)在網站開發中,JavaScript與HTML、CSS一起操作DOM,實現動態效果,並支持如jQuery、React等框架。 2)通過ReactNative和Ionic,JavaScript用於開發跨平台移動應用。 3)Electron框架使JavaScript能構建桌面應用。 4)Node.js讓JavaScript在服務器端運行,支持高並發請求。
