簡介
Next.js 長期以來一直是建立伺服器渲染 React 應用程式的流行選擇。憑藉其對伺服器端渲染 (SSR) 的內建支持,開發人員可以創建動態、SEO 友好的應用程式。然而,Next.js 13 中 App Router 的引入以及 Next.js 14 中的改進顯著簡化和增強了 SSR。
在這篇部落格文章中,我們將探討傳統頁面路由系統和較新的應用程式路由系統之間 SSR 的差異,重點介紹 SSR 的工作原理以及新路由範例如何對其進行更改。
頁面路由中的 SSR (Pre-Next.js 13)
在引入 App Router 之前,SSR 是在頁面路由系統中使用 getServerSideProps 等特定函數來處理的。每個請求都會呼叫此函數,允許開發人員在渲染頁面之前從伺服器端取得資料。
使用 getServerSideProps 的頁路由中的 SSR 範例:
export default function Blogs({ data }) { // Render the fetched data return ( <div> {data.map((item) => ( <div key="{item.id}"> <h3 id="item-title">{item.title}</h3> <p>{item.content}</p> </div> ))} </div> ); } // This function runs on every request export async function getServerSideProps() { // Fetch data from an external API const res = await fetch('https://api.example.com/blogs'); const data = await res.json(); // Pass the data as props to the page component return { props: { data } }; }
這裡,getServerSideProps是Page Routing系統中SSR的關鍵。它允許您在每次請求時從 API(或任何其他資料來源)獲取數據,並將其作為 props 傳遞給頁面元件。這種模式雖然功能強大,但在處理大量伺服器端邏輯和不同的路由時可能會導致複雜的程式碼庫。
Next.js 中的應用程式路由和 SSR 14
在 Next.js 14 中,SSR 變得更加簡化並整合到應用程式路由系統中。這個新系統引入了伺服器元件和客戶端元件,其中 SSR 更加直觀。
在App Routing中,您現在可以直接取得元件內部的數據,而不需要像getServerSideProps這樣的特殊函數。您可以透過使用伺服器操作來實現此目的,這使得程式碼更簡單且更易於維護。
使用伺服器元件的應用程式路由中的 SSR 範例:
"use server"; export async function getBlogs() { try { const response = await fetch('https://api.example.com/posts'); return response.json(); } catch (error) { return { error: error.message }; } } // This component runs on the server and fetches data export default async function Blog() { const blogs = await getBlogs(); return ( <div> {(blogs || []).map((blog) => ( <div key="{blog._id}"> <h3 id="blog-name">{blog.name}</h3> <p>{blog.content}</p> </div> ))} </div> ); }
在此應用程式路由範例中,我們使用伺服器元件透過 use server 直接在元件檔案內取得資料。這樣就不再需要單獨的 API 路由或函數,例如 getServerSideProps.
伺服器操作的力量
Next.js 14 透過引入伺服器操作簡化了流程。這些操作可讓您直接取得和處理元件檔案中的數據,從而降低複雜性並使您的程式碼庫更易於維護。
伺服器操作的主要優點:
更簡潔的程式碼:您可以將所有內容保留在一個地方,而不是將伺服器端邏輯分散在單獨的檔案或函數中。
提高可維護性:移動部件更少意味著需要管理的程式碼更少,從而使您的應用程式更易於維護。
更好的效能:借助智慧型快取機制,您可以微調伺服器端邏輯以獲得最佳效能。
Next.js 中的水合作用
在 Next.js 和伺服器端渲染 (SSR) 的上下文中,水化是指將靜態渲染的 HTML 頁面(從伺服器發送)轉換為瀏覽器中完全互動式 React 應用程式的過程。它使用 React 的客戶端 JavaScript “水合”靜態 HTML,使頁面具有互動性。
應用程式路由與頁面路由中的水合
在頁面路由中,頁面上的每個元件都需要水合作用,使其在客戶端具有互動性。這意味著互動所需的所有 JavaScript 都會發送到客戶端,這可能會隨著應用程式的擴展而導致效能瓶頸。
在應用程式路由中,對於伺服器元件,只有客戶端元件(處理互動性的元件)被水化。這種選擇性水合作用減少了發送到客戶端的 JavaScript 量,從而提高了效能。
應用程式路由中的客戶端元件範例:
'use client'; // Mark this as a client component export default function Button() { return ( <button onclick="{()"> alert('Button clicked!')}>Click Me</button> ); }
這裡,按鈕組件被標記為帶有「use client」的客戶端組件。它允許交互並在客戶端運行,而其他非交互組件仍保留為伺服器組件,從而提高效能。
有關 App Routing 中水合作用的更多信息
其工作原理如下:
Parent Components as Server Components:
The parent components (usually the higher-level components or entire page components) are typically Server Components. They run on the server and handle things like data fetching, rendering static HTML, and passing that data down to child components.
Since these are server-rendered, they do not include any JavaScript on the client-side, and they are not interactive.
Client Components for Interactivity:
Child components, which handle interactivity (like buttons, forms, etc.), are Client Components. These components can use React hooks (useState, useEffect, etc.) and are hydrated on the client-side.
Server Components pass data to these Client Components via props.
Once the HTML is loaded in the browser, Next.js hydrates the Client Components, attaching the necessary event listeners and making the page interactive.
// Server Component (Parent Component) export default async function ParentComponent() { // Fetch data on the server const data = await fetch('https://api.example.com/data').then(res => res.json()); return ( <div> <h1 id="This-is-Server-Side-Rendered">This is Server-Side Rendered</h1> <clientcomponent data="{data}"></clientcomponent> </div> ); } // Client Component (Child Component) 'use client'; import { useState } from 'react'; function ClientComponent({ data }) { const [count, setCount] = useState(0); return ( <div> <p>Data from server: {JSON.stringify(data)}</p> <p>Client-side counter: {count}</p> <button onclick="{()"> setCount(count + 1)}>Increment</button> </div> ); }
Conclusion
Next.js 14 makes Server-Side Rendering (SSR) easier and more powerful with the introduction of server actions in the App Router. By allowing developers to fetch data directly inside component files, this new system streamlines server-side logic, simplifies codebases, and reduces the need for separate API routes. Coupled with selective hydration, SSR in Next.js 14 is now faster and more efficient, helping you build highly dynamic and SEO-friendly applications with ease.
By leveraging these server actions, you can improve your app’s performance while keeping your code clean and maintainable. The shift from Page Routing to App Routing with Server and Client Components represents a major leap forward in building scalable web applications.
以上是Next.js 中的 SSR 應用程式路由與頁面路由相比有何新變化的詳細內容。更多資訊請關注PHP中文網其他相關文章!

Python和JavaScript的主要區別在於類型系統和應用場景。 1.Python使用動態類型,適合科學計算和數據分析。 2.JavaScript採用弱類型,廣泛用於前端和全棧開發。兩者在異步編程和性能優化上各有優勢,選擇時應根據項目需求決定。

選擇Python還是JavaScript取決於項目類型:1)數據科學和自動化任務選擇Python;2)前端和全棧開發選擇JavaScript。 Python因其在數據處理和自動化方面的強大庫而備受青睞,而JavaScript則因其在網頁交互和全棧開發中的優勢而不可或缺。

Python和JavaScript各有優勢,選擇取決於項目需求和個人偏好。 1.Python易學,語法簡潔,適用於數據科學和後端開發,但執行速度較慢。 2.JavaScript在前端開發中無處不在,異步編程能力強,Node.js使其適用於全棧開發,但語法可能複雜且易出錯。

javascriptisnotbuiltoncorc; sanInterpretedlanguagethatrunsonenginesoftenwritteninc.1)JavascriptwasdesignedAsignedAsalightWeight,drackendedlanguageforwebbrowsers.2)Enginesevolvedfromsimpleterterpretpretpretpretpreterterpretpretpretpretpretpretpretpretpretcompilerers,典型地,替代品。

JavaScript可用於前端和後端開發。前端通過DOM操作增強用戶體驗,後端通過Node.js處理服務器任務。 1.前端示例:改變網頁文本內容。 2.後端示例:創建Node.js服務器。

選擇Python還是JavaScript應基於職業發展、學習曲線和生態系統:1)職業發展:Python適合數據科學和後端開發,JavaScript適合前端和全棧開發。 2)學習曲線:Python語法簡潔,適合初學者;JavaScript語法靈活。 3)生態系統:Python有豐富的科學計算庫,JavaScript有強大的前端框架。

JavaScript框架的強大之處在於簡化開發、提升用戶體驗和應用性能。選擇框架時應考慮:1.項目規模和復雜度,2.團隊經驗,3.生態系統和社區支持。

引言我知道你可能會覺得奇怪,JavaScript、C 和瀏覽器之間到底有什麼關係?它們之間看似毫無關聯,但實際上,它們在現代網絡開發中扮演著非常重要的角色。今天我們就來深入探討一下這三者之間的緊密聯繫。通過這篇文章,你將了解到JavaScript如何在瀏覽器中運行,C 在瀏覽器引擎中的作用,以及它們如何共同推動網頁的渲染和交互。 JavaScript與瀏覽器的關係我們都知道,JavaScript是前端開發的核心語言,它直接在瀏覽器中運行,讓網頁變得生動有趣。你是否曾經想過,為什麼JavaScr


熱AI工具

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

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

Undress AI Tool
免費脫衣圖片

Clothoff.io
AI脫衣器

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

熱門文章

熱工具

VSCode Windows 64位元 下載
微軟推出的免費、功能強大的一款IDE編輯器

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

WebStorm Mac版
好用的JavaScript開發工具

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

SAP NetWeaver Server Adapter for Eclipse
將Eclipse與SAP NetWeaver應用伺服器整合。