渲染将你编写的代码转换为用户界面。React 和 Next.js 允许你创建混合 Web 应用,其中部分代码可以在服务器或客户端上渲染。本节将帮助你了解这些渲染环境、策略和运行时之间的差异。
¥Rendering converts the code you write into user interfaces. React and Next.js allow you to create hybrid web applications where parts of your code can be rendered on the server or the client. This section will help you understand the differences between these rendering environments, strategies, and runtimes.
基础知识¥Fundamentals
首先,熟悉三个基本的 Web 概念会很有帮助:
¥To start, it's helpful to be familiar with three foundational web concepts:
你的应用代码可以在 环境 中执行:服务器和客户端。
¥The Environments your application code can be executed in: the server and the client.
当用户访问你的应用或与你的应用交互时启动的 请求-响应生命周期。
¥The Request-Response Lifecycle that's initiated when a user visits or interacts with your application.
网络边界 分隔服务器和客户端代码。
¥The Network Boundary that separates server and client code.
渲染环境¥Rendering Environments
有两种可以渲染 Web 应用的环境:客户端和服务器。
¥There are two environments where web applications can be rendered: the client and the server.
客户端是指用户设备上的浏览器,它向服务器发送请求以获取应用代码。然后它将来自服务器的响应转换为用户界面。
¥The client refers to the browser on a user's device that sends a request to a server for your application code. It then turns the response from the server into a user interface.
服务器是指数据中心中存储应用代码、接收来自客户端的请求并发回适当响应的计算机。
¥The server refers to the computer in a data center that stores your application code, receives requests from a client, and sends back an appropriate response.
从历史上看,开发者在为服务器和客户端编写代码时必须使用不同的语言(例如 JavaScript、PHP)和框架。通过 React,开发者可以使用相同的语言(JavaScript)和相同的框架(例如 Next.js 或你选择的框架)。这种灵活性使你可以无缝地为两种环境编写代码,而无需上下文切换。
¥Historically, developers had to use different languages (e.g. JavaScript, PHP) and frameworks when writing code for the server and the client. With React, developers can use the same language (JavaScript), and the same framework (e.g. Next.js or your framework of choice). This flexibility allows you to seamlessly write code for both environments without context switching.
但是,每个环境都有其自己的一组功能和限制。因此,你为服务器和客户端编写的代码并不总是相同的。有些操作(例如数据获取或管理用户状态)比另一种环境更适合一种环境。
¥However, each environment has its own set of capabilities and constraints. Therefore, the code you write for the server and the client is not always the same. There are certain operations (e.g. data fetching or managing user state) that are better suited for one environment over the other.
了解这些差异是有效使用 React 和 Next.js 的关键。我们将在 服务器 和 客户 组件页面上更详细地介绍差异和用例,现在,让我们继续在我们的基础上进行构建。
¥Understanding these differences is key to effectively using React and Next.js. We'll cover the differences and use cases in more detail on the Server and Client Components pages, for now, let's continue building on our foundation.
请求-响应生命周期¥Request-Response Lifecycle
一般来说,所有网站都遵循相同的请求-响应生命周期:
¥Broadly speaking, all websites follow the same Request-Response Lifecycle:
用户操作:用户与 Web 应用交互。这可以是单击