使用 expo-linking API
了解如何在 Expo 的服务器上渲染 React 组件。
在 SDK 52 及更高版本 中可实验性使用。这是测试版本,可能会有破坏性更改。
React Server Components 启用了许多令人兴奋的功能,包括:
🌐 React Server Components enable a number of exciting capabilities, including:
- 使用异步组件和 React Suspense 进行数据提取。
- 使用密钥和服务器端 API。
- 用于 SEO 和性能的服务器端渲染 (SSR)。
- 构建时渲染以删除未使用的 JS 代码。
Expo Router 在所有平台上都支持 React 服务器组件。这是一个功能的早期预览版本,该功能将在 Expo Router 中默认启用。
🌐 Expo Router enables support for React Server Components on all platforms. This is an early preview of a feature that will be enabled by default in Expo Router.
先决条件
🌐 Prerequisites
你的项目必须使用 Expo Router 和 React Native 新架构(SDK 52 起默认)。
🌐 Your project must use Expo Router and React Native new architecture (default from SDK 52).
用法
🌐 Usage
要在 Expo 应用中使用 React Server Components,你需要:
🌐 To use React Server Components in your Expo app, you need to:
-
安装所需的 RSC 依赖
Terminal-npx expo install react-server-dom-webpack -
确保在 package.json 中入口模块为
expo-router/entry(默认)。 -
在项目应用配置中启用标志:
{ "expo": { "experiments": { "reactServerFunctions": true } } }
- 确保在你的应用配置中,
"origin"未被设置为布尔值。 - 创建初始路由 app/index.tsx:
/// <reference types="react/canary" /> import React from 'react'; import { ActivityIndicator } from 'react-native'; import renderInfo from '../actions/render-info'; export default function Index() { return ( <React.Suspense fallback={ // The view that will render while the Server Function is awaiting data. <ActivityIndicator /> }> {renderInfo({ name: 'World' })} </React.Suspense> ); }
- 创建一个服务器函数 actions/render-info.tsx:
'use server'; import { Text } from 'react-native'; export default async function renderInfo({ name }) { // Securely fetch data from an API, and read environment variables... return <Text>Hello, {name}!</Text>; }
服务器函数的视图返回值是将流式传输到客户端的 React 服务器组件有效负载。
🌐 The views return value of the Server Function is a React Server Component payload that will be streamed to the client.
在开发者预览期间,应用配置中的
web.output必须为single。更多输出模式的支持即将推出。
设置提供程序
🌐 Server Components
服务器组件运行在服务器上,这意味着它们可以访问服务器 API 和 Node.js 内置模块(在本地运行时)。它们也可以使用异步组件。
🌐 Server Components run in the server, meaning they can access server APIs and Node.js built-ins (when running locally). They can also use async components.
考虑以下获取数据并渲染数据的组件:
🌐 Consider the following component which fetches data and renders it:
import 'server-only'; import { Image, Text, View } from 'react-native'; export async function Pokemon() { const res = await fetch('https://pokeapi.co/api/v2/pokemon/2'); const json = await res.json(); return ( <View style={{ padding: 8, borderWidth: 1 }}> <Text style={{ fontWeight: 'bold', fontSize: 24 }}>{json.name}</Text> <Image source={{ uri: json.sprites.front_default }} style={{ width: 100, height: 100 }} /> {json.abilities.map(ability => ( <Text key={ability.ability.name}>- {ability.ability.name}</Text> ))} </View> ); }
要将其渲染为服务器组件,你需要从服务器函数返回它。
🌐 To render this as a server component, you'll need to return it from a Server Function.
关键点
🌐 Key points
- 你不能在服务器组件中使用像
useState、useEffect或useContext这样的钩子。 - 你无法在服务器组件中使用浏览器或原生 API。
"use server"并不是用来将文件标记为服务器组件的。它是用来标记一个文件中导出了 React 服务器函数。- 服务器组件可以访问所有环境变量,因为它们安全地从客户端运行。
客户端组件
🌐 Client Components
由于服务器组件无法访问本地 API 或 React 上下文,你可以创建一个客户端组件来使用这些功能。方法是在文件顶部使用 "use client" 指令来创建它们。
🌐 Since Server Components cannot access native APIs or React Context, you can create a Client Component to use these features. They are created by marking files with the "use client" directive at the top.
'use client'; import { Text } from 'react-native'; export default function Button({ title }) { return <Text onPress={() => {}}>{title}</Text>; }
此模块可以导入并在服务器功能或服务器组件中使用。
🌐 This module can be imported and used in a Server Function or Server Component.
关键点
🌐 Key point
你不能将函数作为属性传递给服务器组件。你只能传递可序列化的数据。
🌐 You cannot pass functions as props to Server Components. You can only pass serializable data.
接收事件
🌐 React Server Functions
服务器函数是运行在服务器上的函数,可以从客户端组件中调用。可以把它们看作是更易编写的全类型 API 路由。
🌐 Server Functions are functions that run on the server and can be called from Client Components. Think of them like fully-typed API routes that are easier to write.
它们必须始终是异步函数,并在函数顶部标记为 "use server"。
🌐 They must always be an async function and are marked with "use server" at the top of the function.
export default function Index() { return ( <Button title="按我" onPress={async () => { 'use server'; // This code runs on the server. console.log('Button pressed'); return '...'; }} /> ); }
你可以创建客户端组件来调用服务器函数:
🌐 You can create a Client Component to invoke the Server Function:
'use client'; import { Text } from 'react-native'; export default function Button({ title, onPress }) { return <Text onPress={() => onPress()}>{title}</Text>; }
服务器功能也可以在独立文件中定义(在顶部使用 "use server"),并从客户端组件中导入:
🌐 Server Functions can also be defined in a standalone file (with "use server" at the top) and imported from Client Components:
'use server'; export async function callAction() { // ... }
这些可以在客户端组件中使用:
🌐 These can be used in a Client Component:
import { Text } from 'react-native'; import { callAction } from './server-actions'; export default function Button({ title }) { return <Text onPress={() => callAction()}>{title}</Text>; }
关键点
🌐 Key points
- 你只能将可序列化的数据作为参数传递给服务器函数。
- 服务器函数只能返回可序列化的数据。
- 服务器函数在服务器上运行,是放置不应暴露给客户端的逻辑的好地方。
- 服务器函数目前不能在 DOM 组件内部使用
渲染路由
🌐 Rendering in Server Functions
Expo Router 中的 React 服务器函数可以在服务器上渲染 React 组件,并将 RSC 有效负载(一种由 React 团队维护的类似 JSON 的自定义格式)流式传回客户端进行渲染。这类似于网页上的服务端渲染(SSR)。
🌐 React Server Functions in Expo Router can render React components on the server and stream back an RSC payload (a custom JSON-like format that's maintained by the React team) for rendering on the client. This is similar to server-side rendering (SSR) on the web.
例如,以下服务器函数将渲染一些文本:
🌐 For example, the following Server Function will render some text:
'use server'; // Optional: Import "server-only" for sanity. import 'server-only'; import { View, Image, Text } from 'react-native'; export async function renderProfile({ username, accessToken, }: { username: string; accessToken: string; }) { // NOTE: Rate limits, GDPR, and other server-side operations can be done here. // Fetch some data securely from an API. const { name, image } = await fetch(`https://api.example.com/profile/${username}`, { headers: { Authorization: `Bearer ${accessToken}`, // Use secret environment variables securely as this code will live on the server. // The EXPO_PUBLIC_ prefix is not required here. 'X-Secret': process.env.SECRET, }, }).then(res => res.json()); // Render return ( <View> <Image source={{ uri: image }} /> <Text>{name}</Text> </View> ); }
此服务器函数可以从客户端组件调用,内容将流回客户端:
🌐 This Server Function can be invoked from a Client Component and the contents will be streamed back to the client:
'use client'; import { useLocalSearchParams } from 'expo-router'; import * as React from 'react'; import { Text } from 'react-native'; import { renderProfile } from '@/components/server-actions'; // Loading state that renders while data is being fetched. function Fallback() { return <Text>Loading...</Text>; } export default function Profile() { const { username } = useLocalSearchParams(); const { accessToken } = useCustomAuthProvider(); // Call the Server Function with the username and access token. const profile = React.useMemo( () => renderProfile({ username, accessToken }), [username, accessToken] ); // Render the profile asynchronously with React Suspense and a custom loading state. return <React.Suspense fallback={<Fallback />}>{profile}</React.Suspense>; }
库兼容性
🌐 Library compatibility
并非所有库都已针对 React 服务器组件进行优化。你可以使用 "use client" 指令将文件标记为客户端组件,并在服务器组件中使用它。这可以用来临时解决兼容性问题。
🌐 Not all libraries are optimized for React Server Components yet. You can use the "use client" directive to mark a file as a Client Component and use it in a Server Component. This can be used to temporarily workaround compatibility issues.
例如,考虑一个名为 react-native-unoptimized 的库,它尚未随 "use client" 指令一起发布。你可以通过创建一个模块并重新导出每个模块来解决这个问题:
🌐 For example, consider a library react-native-unoptimized that does not ship with "use client" directives yet. You can workaround this by creating a module and re-exporting each module:
// This directive opts the module into client-side rendering. 'use client'; // Re-exporting the imports from the library. export { One, Two, Three } from 'react-native-unoptimized';
避免使用 export * from '...',因为这会破坏服务器与客户端之间互操作的一些内部机制。
🌐 Avoid using export * from '...' as this breaks some of the internals of interopting between the server and client.
标记为 "use client" 的模块无法从服务器组件中通过点访问。这意味着在服务器上执行 StyleSheet.create 或 Platform.OS 等操作将不起作用,除非对 react-native 包进行进一步优化。
🌐 Modules marked with "use client" cannot be dot-accessed from Server Components. This means operations like StyleSheet.create or Platform.OS will not work on the server without further optimization in the react-native package.
切换标签
🌐 Suspense
你可以使用 React Suspense 在等待数据加载时从服务器流回部分 UI。
🌐 You can stream back partial UI from the server while waiting for data to load by using React Suspense.
在以下示例中,客户端会立即返回一个 Loading... 文本,当 <MediumTask> 在一秒后完成渲染时,它将用 Medium task done! 替换文本。<ExpensiveTask> 需要三秒加载时间,加载完成后将用 Expensive task done! 替换文本。
🌐 In the following example, a Loading... text is returned instantly on the client, and when the <MediumTask> finishes rendering one second later, it will replace the text with Medium task done!. The <ExpensiveTask> will take three seconds to load, and when it finishes, it will replace the text with Expensive task done!.
import { Suspense } from 'react'; import { renderMediumTask, renderExpensiveTask } from '@/actions/tasks'; export default function App() { return <Suspense fallback={<Text>Loading...</Text>}>{renderTasks()}</Suspense>; }
'use server'; export async function renderTasks() { return ( <Suspense fallback={<Text>Loading...</Text>}> <> <MediumTask /> <Suspense fallback={<Text>Loading...</Text>}> <ExpensiveTask /> </Suspense> </> </Suspense> ); } async function MediumTask() { // Wait one second before resolving. await new Promise(resolve => setTimeout(resolve, 1000)); return <Text>Medium task done!</Text>; } async function ExpensiveTask() { // Wait three seconds before resolving. await new Promise(resolve => setTimeout(resolve, 3000)); return <Text>Expensive task done!</Text>; }
如果你移除 <ExpensiveTask> 外层的 Suspense,你会看到 Loading... 会等待两个组件都渲染完成后再更新 UI。这使你能够逐步控制加载状态。有时,一次性等待所有内容加载完是有意义的(大多数情况下),而有时,一旦你有部分内容就立即返回 UI 会更有利(比如 ChatGPT 中的文本响应)。
🌐 If you remove the Suspense wrapper around <ExpensiveTask>, you'll see that the Loading... waits for both components to finish rendering before updating the UI. This enables you to control the loading state incrementally. Sometimes, it makes sense to wait for everything to load at once (most of the time), while other times, it is beneficial to stream back UI as soon as you have (like the text response in ChatGPT).
秘密
🌐 Secrets
服务器组件可以访问秘密和服务器端 API。你可以使用 process.env 对象来访问环境变量。通过在项目中导入 server-only 模块,你可以确保某个模块永远不会在客户端运行。
🌐 Server Components can access secrets and server-side APIs. You can use the process.env object to access environment variables. You can ensure a module never runs on the client by importing the server-only module in your project.
// This will assert if the module runs on the client. import 'server-only'; import { Text } from 'react-native'; export async function renderData() { // This code only runs on the server. const data = await fetch('https://my-endpoint/', { headers: { Authorization: `Bearer ${process.env.SECRET}`, }, }); // ... return <div />; }
你可以在你的 .env 文件中定义密钥:
🌐 You can define the secret in your .env file:
SECRET=123
你无需重启开发服务器即可更新环境变量。它们会在每次请求时自动重新加载。
平台检测
🌐 Platform detection
要检测你的代码是为哪个平台打包的,请使用 process.env.EXPO_OS 环境变量。例如,process.env.EXPO_OS === 'ios'。建议使用它而不是 Platform.OS,因为 react-native 尚未针对 React 服务器组件完全优化,可能无法按预期工作。
🌐 To detect which platform your code is bundled for, use the process.env.EXPO_OS environment variable. For example, process.env.EXPO_OS === 'ios'. Prefer this to Platform.OS as react-native is not fully optimized for React Server Components yet and won't work as expected.
你可以通过执行 typeof window === 'undefined' 检查来检测代码是否在服务器上运行。这在客户端设备上总是返回 true,在服务器上返回 false。
🌐 You can detect if code is running on the server by performing a typeof window === 'undefined' check. This will always return true on client devices and false on the server.
教程:创建原生模块
🌐 Testing with jest
库作者可以通过使用 jest-expo 测试他们的模块是否支持服务器组件。详细信息请参阅 测试 React 服务器组件 指南。
🌐 Library authors can test their modules support Server Components by using jest-expo. Learn more in the Testing React Server Components guide.
元数据
🌐 Metadata
React 服务器组件是 React 19 的一项功能。要启用它们,Expo CLI 会在所有平台上自动使用 React 的特殊试验版本。未来,当 React Native 默认使用 React 19 时,这一功能将被移除。
🌐 React Server Components are a feature of React 19. To enable them, Expo CLI automatically uses a special canary build of React on all platforms. In the future, it will be removed when React 19 is enabled by default in React Native.
因此,你可以使用 React 19 的功能,例如在应用中的任何位置放置 <meta> 标签(仅限网页)。
🌐 As a result, you can use React 19 features such as placing <meta> tags anywhere in your app (web-only).
export default function Index() { return ( <> {process.env.EXPO_OS === 'web' && ( <> <meta name="description" content="Hello, world!" /> <meta property="og:image" content="/og-image.png" /> </> )} <MyComponent /> </> ); }
你可以使用这个来替代 expo-router/head 的 Head 组件,但目前它仅在网页上可用。
🌐 You can use this instead of the Head component from expo-router/head, but it only works on web for now.
请求查询参数
🌐 Request headers
你可以使用 expo-router/rsc/headers 模块访问用于向服务器组件发出请求的请求头。
🌐 You can access the request headers used to make the request to the Server Component using the expo-router/rsc/headers module.
import { unstable_headers } from 'expo-router/rsc/headers'; export async function renderHome() { const authorization = (await unstable_headers()).get('authorization'); return <Text>{authorization}</Text>; }
unstable_headers 函数返回一个 Promise,该 Promise 会解析为只读的 Headers 对象。
🌐 The unstable_headers function returns a promise that resolves to a read-only Headers object.
关键点
🌐 Key points
- 由于请求会动态更改头信息,此 API 不能与构建时渲染(
render: 'static')一起使用。将来,如果输出模式为static,此 API 将会报错。 unstable_headers仅限服务器使用,不能在客户端使用。
完整 React Server Components 模式
🌐 Full React Server Components mode
重要 此模式为实验性功能。
启用完整的 React 服务器组件支持可以让你利用更多功能。在此模式下,路由的默认渲染模式是服务器组件,而不是客户端组件。它仍在开发中,因为路由和 React Navigation 需要重写以支持并发。
🌐 Enabling full React Server Components support allows you to leverage even more features. In this mode, the default rendering mode for routes is server components instead of client components. It is still in development, as the Router and React Navigation need to be rewritten to support concurrency.
要启用完整的服务器组件模式,你需要在应用配置中启用 reactServerComponentRoutes 标志:
🌐 To enable full Server Components mode, you need to enable the reactServerComponentRoutes flag in the app config:
{ "expo": { "experiments": { "reactServerFunctions": true, "reactServerComponentRoutes": true } } }
启用此功能后,所有路由将默认渲染为服务器组件。未来,这将减少服务器/客户端的瀑布加载,并启用构建时渲染,以提供更好的离线支持。
🌐 With this enabled, all routes will render as Server Components by default. In the future this will reduce server/client waterfalls and enable build-time rendering to provide better offline support.
- 当前没有堆栈路由。自定义布局
Stack、Tabs和Drawer还不支持服务器组件。 - 大多数
Link组件属性尚不支持。
在服务器功能中渲染
🌐 Reloading Server Components
这仅限于完整的 React 服务器组件模式。
在开发环境中,服务器组件会在每次请求时重新加载。这意味着你可以对服务器组件进行更改,并立即在客户端运行时看到这些更改的效果。你可能希望通过编程方式手动触发重新加载事件,以重新获取数据或重新渲染组件。这可以使用 useRouter 钩子中的 router.reload() 函数来实现。
🌐 Server Components are reloaded on every request in development. This means that you can make changes to your server components and see them reflected immediately in the client runtime. You may want to manually trigger a reload event programmatically to refetch data or re-render the component. This can be done using the router.reload() function from the useRouter hook.
'use client'; import { useRouter } from 'expo-router'; import { Text } from 'react-native'; export function Button() { const router = useRouter(); return ( <Text onPress={() => { // Reload the current route. router.reload(); }}> Reload current route </Text> ); }
如果该路由在构建时已渲染,它将不会在客户端重新渲染。这是因为渲染代码未包含在生产服务器中。
🌐 If the route was rendered at build-time, it will not be re-rendered on the client. This is because the rendering code is not included in the production server.
构建时渲染
🌐 Build-time rendering
这仅限于完整的 React 服务器组件模式。
Expo Router 支持两种不同的服务器组件渲染模式:构建时渲染和请求时渲染。这些模式可以通过在每条路由上使用 unstable_settings 导出来指定:
🌐 Expo Router supports two different modes of rendering Server Components: build-time rendering and request-time rendering. These modes can be indicated on a per-route basis by using the unstable_settings export:
import { Text, View } from 'react-native'; export const unstable_settings = { // This component will be rendered at build-time and never re-rendered in production. render: 'static', }; export default function Index() { return ( <View> <Text>Hello, world!</Text> </View> ); }
render: 'static'会在构建时渲染组件,并且在生产环境中不会重新渲染它。这类似于经典的静态站点生成器的工作方式。render: 'dynamic'会在请求时渲染组件,并在每次请求时重新渲染它。这与服务器端渲染的工作方式类似。
如果你想要客户端渲染,请将数据提取移动到客户端组件并在本地控制渲染。
🌐 If you want client-side rendering, move your data fetching to a Client Component and control the rendering locally.
标记为 static 输出的路由将在构建时呈现并嵌入本地二进制文件。这使得可以在不发出服务器请求的情况下呈现路由(因为服务器请求已在应用下载时完成)。
🌐 Routes marked with static output will be rendered at build-time and embedded in the native binary. This enables rendering routes without making a server request (because the server request was made when the app was downloaded).
当前默认是 dynamic 渲染。未来,我们将使缓存和优化更智能、更自动化。
🌐 The current default is dynamic rendering. In the future, we'll change the caching and optimizations to be smarter and more automatic.
你可以使用 generateStaticParams 函数在构建时生成静态页面。这对于那些必须只在构建时运行而不在服务器上运行的组件非常有用。
🌐 You can generate static pages at build-time with the generateStaticParams function. This is useful for components that must only run at build-time and not on the server.
import { Text } from 'react-native'; // Adding `unstable_settings.render: 'static'` will prevent this component from running on the server. export const unstable_settings = { render: 'static', }; // This function will generate static pages for each shape. export async function generateStaticParams() { return [{ shape: 'square' }]; } export default function ShapeRoute({ shape }) { return <Text>{shape}</Text>; }
CSS
这仅限于完整的 React 服务器组件模式。
Expo Router 支持在服务器组件中导入全局 CSS 和 CSS 模块。
🌐 Expo Router supports importing global CSS and CSS modules in Server Components.
import './styles.css'; import styles from './styles.module.css'; export default function Index() { return <div className={styles.container}>Hello, world!</div>; }
CSS 将从服务器提升到客户端包中。
🌐 The CSS will be hoisted into the client bundle from the server.
部署
🌐 Deployment
通用 React 服务器组件仍处于测试版。
Web
首先,构建 Web 项目:
🌐 First, build the web project:
- npx expo export -p web然后你可以使用 npx expo serve 在本地托管它,或者将其部署到云端:
🌐 Then you can host it locally with npx expo serve or deploy it to the cloud:
EAS Hosting 是部署你的 Expo API 路由和服务器的最佳方式。
原生
🌐 Native
你可以按照服务器部署指南部署原生 React 服务器组件:
🌐 You can deploy your native React Server Components by following the server deployment guide:
将版本化服务器部署并链接到你的生产原生应用。
已知的限制
🌐 Known limitations
这是一个我们正在积极开发的非常早期的技术预览版本。
- Expo Snack 不支持打包服务器组件。
- EAS 更新尚未与服务器组件配合使用。
- DOM 组件目前无法在生产中使用 React 服务器函数。
- 生产部署受到限制,目前不推荐。
- 服务器端渲染 RSC 数据到 HTML 尚不支持。这意味着静态输出和服务器输出尚未完全可用。
generateStaticParams在完整的 React 服务器组件模式下仅部分支持。- HTML
form与服务器功能的集成尚不支持(这部分功能可以自动工作,但数据未加密)。 StyleSheet.create和Platform.OS在本地不支持。请使用标准对象进行样式设置,并使用process.env.EXPO_OS进行平台检测。- 在 Hermes 上不支持调用其他服务器函数的 React 服务器函数,这是由于 Hermes 运行时的限制。使用静态 Hermes 可能可以解决此问题。