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>; }
Serverfunktion in der Serverkomponente deklarieren
import Button from './Button'; function EmptyNote () { async function createNoteAction() { // Server Function 'use server'; await db.notes.create(); } return <Button onClick={createNoteAction}/>; }
Serverfunktion in der separaten Datei deklarieren
"use server"; export async function updateName(name) { if (!name) { return {error: 'Name is required'}; } await db.users.updateName(name); }
Verwendung der Serverfunktion in der Client-Komponente
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>; }
Type | use client | use server | Notes |
---|---|---|---|
string | ✅ | ✅ | both string value and iterables are supported. |
number | ✅ | ✅ | |
bigint | ✅ | ✅ | |
boolean | ✅ | ✅ | |
undefined | ✅ | ✅ | |
null | ✅ | ✅ | |
Array | ✅ | ✅ | Only available in the item of serializable list. |
Map | ✅ | ✅ | Only available in the item of serializable list. |
Set | ✅ | ✅ | Only available in the item of serializable list. |
TypedArray | ✅ | ✅ | |
ArrayBuffer | ✅ | ✅ | |
Date | ✅ | ✅ | |
object | ✅ | ✅ | Support only plain object(object initializers or JSON), null prototype not supported. |
Promises | ✅ | ✅ | Only available in the serializable list. |
ReactNode | ✅ | ❌ | Only Server Component can send it to Client Component via props. |
FormData | ❌ | ✅ | Only server functions can return FormData instance. |
symbol | ⚠️ | ⚠️ | Only symbols registered in the global Symbol registry via Symbol.for |
function | ⚠️ | ⚠️ | Only server functions allowed. |
class | ❌ | ❌ | Any instance objects are not serializable. |
Viel Spaß beim Reagieren!
Das obige ist der detaillierte Inhalt vonEin Spickzettel für React-Serverfunktionen. Für weitere Informationen folgen Sie bitte anderen verwandten Artikeln auf der PHP chinesischen Website!