?大家好!
React.js 是用於建立使用者介面的最受歡迎的 JavaScript 程式庫之一。雖然 React 社群有詳細記錄,但仍有一些鮮為人知的主題和概念。
我們泡茶或咖啡吧,出發吧!
React Server Components (RSC) 是 React 團隊推出的一項新的實驗性功能,用於優化渲染效能。它們允許開發人員建立在伺服器上呈現的應用程式的一部分,同時仍維護 React 元件模型。
它在與客戶端或 SSR 伺服器不同的環境中運行,並且可以在 CI 伺服器上建置時調用一次,或者可以使用 Web 伺服器針對每個請求運行它們。
透過 React Server 元件的強大功能,我們可以直接在 React 元件中讀取檔案內容。
下面,有一個簡單的例子,我們該怎麼做。
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>; }
客戶端只會看到檔案的渲染輸出。這意味著內容在第一頁載入期間是可見的,並且捆綁包不包含渲染靜態內容所需的昂貴的庫(標記為 sanitize-html)。
使用伺服器元件,我們可以與資料庫通信,取得任何資料並在客戶端中使用。我們也可以在 Next.js 應用程式中做到這一點,整合任何 ORM。
下面是一個使用伺服器元件從資料庫取得資料的簡單範例。
import db from './database'; async function Note({id}) { // NOTE: loads *during* render. const note = await db.notes.get(id); return ( <div> <Author> <p>In database file there can be implementation of data query from database.<br> For example:<br> </p> <pre class="brush:php;toolbar:false">const db = { notes: { get: async (id) => { return dbClient.query('SELECT * FROM notes WHERE id = ?', [id]); } }, authors: { get: async (id) => { return dbClient.query('SELECT * FROM authors WHERE id = ?', [id]); } } };
然後,捆綁器將資料、渲染的伺服器元件和動態用戶端元件組合成一個捆綁包。當頁面載入時,瀏覽器看不到原始的Note和Author元件;僅渲染的輸出傳送到客戶端。 伺服器元件可以透過從伺服器重新取得它們來動態化,它們可以存取資料並再次渲染。
伺服器元件引進了一種使用 async/await 編寫元件的新方法。當您在非同步元件中等待時,React 將暫停並等待承諾解決,然後再恢復渲染。這可以跨伺服器/客戶端邊界工作,並支援 Suspense 的串流。
伺服器元件範例:
// Server Component import db from './database'; async function Page({id}) { // Will suspend the Server Component. const note = await db.notes.get(id); // NOTE: not awaited, will start here and await on the client. const commentsPromise = db.comments.get(note.id); return ( <div> {note} <Suspense fallback={<p>Loading Comments...</p>}> <Comments commentsPromise={commentsPromise} /> </Suspense> </div> ); } // Client Component "use client"; import {use} from 'react'; function Comments({commentsPromise}) { // NOTE: this will resume the promise from the server. // It will suspend until the data is available. const comments = use(commentsPromise); return comments.map(commment => <p>{comment}</p>); }
評論的優先順序較低,因此我們在伺服器上啟動 Promise,並使用 *use * API 在客戶端等待它。這將在客戶端掛起,而不會阻止筆記內容的渲染。
在接下來的部分中,我們將討論伺服器操作和指令(「使用客戶端」、「使用伺服器」)的功能,以及為什麼「使用伺服器」與「使用客戶端」沒有相同的角色?
再見!
雖然伺服器元件仍處於實驗階段,但它們因其改進大規模應用程式的潛力而逐漸受到關注。它們消除了將不必要的 JavaScript 傳送到客戶端的需要,從而實現更快的載入時間和更流暢的使用者體驗。
以上是釋放 React 伺服器元件的力量 |第 1 部分的詳細內容。更多資訊請關注PHP中文網其他相關文章!