跳到正文
产品桌面工具TASTECAD图纸查看TASTEFILES文件管理TASTEFTP文件传输TASTESSH远程工作空间TASTEZIP压缩与解压TASTEWINM文件管理开发工具TASTECODERust 集成开发环境TASTESTUDIO集成开发与测试环境TASTEETL数据整合(ETL)服务器TASTEREMOTE远程桌面服务器TASTEGEO空间信息服务器TASTEMAIL邮件工作空间投资TASTESTOCK股票自动交易桌面应用开始使用下载文档购买全部产品
市场
资讯
技术资讯今日开发资讯开发文档编程语言RustTypeScriptJavaScriptPythonGoC#JavaCC++KotlinDartWeb 前端框架Next.jsReactVue.js · NuxtSvelteKitAngular服务端框架Spring BootDjangoFastAPIASP.NET CoreNestJS · Express应用与桌面框架TauriFlutterReact NativeElectron算法算法基础核心算法进阶算法实用算法
社区项目开发日志提示词AI 工具问题作品展示社区指南
合作技术传授网站构建桌面应用构建发布与支付流水线销售合作伙伴联系我们
服务远程桌面安装包定制
TASTEDEV
产品

桌面工具

TASTECAD复杂图纸,轻松打开TASTEFILES只要需要的文件,最快送达TASTEFTP让文件往来,干净利落TASTESSH你与服务器之间,连接更牢靠TASTEZIP压得更快,解得更稳TASTEWINM以键盘为主、用两个窗格整理文件的文件管理器

开发工具

TASTECODE在一个窗口中完成 Rust 应用的编辑、构建、调试和测试TASTESTUDIO从编辑到远程测试,再到经批准的 AI 修复TASTEETL边看数值,边搬数据

服务器

TASTEREMOTE在自己的服务器上运行的远程桌面TASTEGEO用 Rust 重新构建兼容 GeoServer 的空间信息服务器TASTEMAIL把邮件的主导权拿回自己手中

投资

TASTESTOCK何时、做什么——按你定下的规则运行的股票自动交易

开始使用

下载所有产品的最新版本文档各产品使用方法购买订阅与永久许可全部产品一览全部产品
全部产品
市场资讯
技术

资讯

今日开发资讯语言、框架、GitHub 与 AI 官方发布开发文档语言、框架与算法指南

编程语言

RustTypeScriptJavaScriptPythonGoC#JavaCC++KotlinDart

框架

Web 前端框架Next.jsReactVue.js · NuxtSvelteKitAngular
服务端框架Spring BootDjangoFastAPIASP.NET CoreNestJS · Express
应用与桌面框架TauriFlutterReact NativeElectron

算法

算法基础复杂度分析 · 排序 · 查找 · 基础数据结构 · 树与堆核心算法图遍历 · 最短路径与最小生成树 · 动态规划 · 贪心算法 · 分治法 · 回溯法进阶算法字符串算法 · 数学与数论 · 位运算 · 线段树 · 并查集实用算法编程面试解题策略 · LRU 缓存 · 限流 · 一致性哈希
查看全部开发文档
社区
项目发现开发者与作品开发日志决策与试错提示词可复用的指令AI 工具问题Claude、Codex、Gemini 的问题与变通办法作品展示已完成的成果社区指南我们如何公开构建
合作
技术传授用 Rust 和 egui 打造原生应用网站构建10 种语言、账户、文档与下载桌面应用构建Rust 和 egui,不用 WebView发布与支付流水线签名、MSI、deb、rpm、AppImage、哈希销售合作伙伴推荐即得 30%联系我们开发、合作与投资咨询
服务
远程桌面用浏览器连接你的电脑安装包定制只装需要的,设置预先放好
购买
ZH
한국어EnglishDeutschEspañolFrançaisItalianoPortuguês (Brasil)日本語简体中文繁體中文
登录
登录
TASTEDEV

从小工具到更好的开发。

support@tastedev.net支持 TASTEDEV
产品产品线购买文档下载市场客户支持
社区项目开发日志提示词AI 工具问题作品展示
政策关于我们隐私政策服务条款订阅条款退款政策社区规范
账户登录注册
访客
今天
昨天
累计浏览
公司名称
GXSOFT
法定代表人
CHOI YOUNG GU
营业执照号
853-44-00368
地址
9F V24, 351 Gyeongin-ro, Michuhol-gu, Incheon, Republic of Korea
电话
+82-10-4404-1523
电子邮件
whitecalvin@tastedev.net
个人信息保护负责人
CHOI YOUNG GU

© 2026 TASTEDEV产品信息以已验证的开发源码为准。已发布·持续改进

Next.js 文档
Next.js
Getting Started with Next.jsProject StructureCore ConceptsData and StateTestingDeployment
讨论

Next.js 指南 · 4/6

Data and State

本章目前仅提供英文版。

In Next.js, reads usually happen in Server Components, writes in Server Actions or Route Handlers, and browser-only UI state lives in Client Components. This chapter covers fetching, caching, Route Handlers, forms and client state.

Fetching data in Server Components

Server Components can be async, so you await data right inside them, with fetch or an ORM or database client. The code runs only on the server, so secrets never reach the browser.

// app/products/page.tsx
import { db } from "@/lib/db";

export default async function ProductsPage() {
  const [products, categories] = await Promise.all([
    db.product.findMany({ take: 20 }),
    fetch("https://api.example.com/categories").then((res) => res.json()),
  ]);

  return (
    <main>
      <p>{categories.length} categories</p>
      <ul>
        {products.map((p) => (
          <li key={p.id}>{p.name}</li>
        ))}
      </ul>
    </main>
  );
}

Start independent requests together with Promise.all; awaiting them one by one creates a waterfall. Keeping data access in lib/ functions makes reuse and authorization checks easier.

Caching and revalidation

Caching is the part of Next.js that has changed most between major versions. In recent releases fetch results are not cached by default; you opt in where it makes sense. The commonly used fetch options are:

// cache the result and reuse it
await fetch("https://api.example.com/menu", { cache: "force-cache" });

// time-based revalidation: refresh at most once an hour
await fetch("https://api.example.com/news", { next: { revalidate: 3600 } });

// tag the data so you can invalidate just this tag later
await fetch("https://api.example.com/posts", { next: { tags: ["posts"] } });

After a mutation, invalidate the cache so users see fresh content. revalidatePath from next/cache invalidates a route, and revalidateTag invalidates tagged data (recent releases take a second argument that controls how revalidation behaves).

The newest releases also offer an opt-in model: enable the cacheComponents option and put a "use cache" directive at the top of a function or component. In that model, cacheLife sets how long an entry lives and cacheTag attaches tags. Check which model your project uses and follow the docs for that version.

Route Handlers

When you need an HTTP response such as JSON rather than UI, export functions named after HTTP methods from a route.ts file. They use the standard Web Request and Response APIs and suit public APIs and webhooks. A folder cannot contain both and .

对本章有疑问?
上一章Core Concepts下一章Testing
page.tsx
route.ts
// app/api/posts/route.ts
import { db } from "@/lib/db";

export async function GET() {
  const posts = await db.post.findMany();
  return Response.json(posts);
}

export async function POST(request: Request) {
  const body = await request.json();
  const post = await db.post.create({ data: { title: body.title } });
  return Response.json(post, { status: 201 });
}

Server Components should call data functions directly rather than fetch your own Route Handlers.

Forms with Server Actions

Server Actions are a natural fit for form submissions and mutations. Put them in a separate file and Client Components can import them too. React's useActionState hook gives you both the value the action returns (such as an error message) and a pending flag.

// app/actions.ts
"use server";

import { revalidatePath } from "next/cache";
import { redirect } from "next/navigation";
import { db } from "@/lib/db";

export async function createPost(prev: { error?: string }, formData: FormData) {
  const title = String(formData.get("title") ?? "").trim();
  if (!title) return { error: "Please enter a title." };
  await db.post.create({ data: { title } });
  revalidatePath("/posts");
  redirect("/posts");
}
// app/posts/new/form.tsx
"use client";

import { useActionState } from "react";
import { createPost } from "@/app/actions";

export function NewPostForm() {
  const [state, formAction, pending] = useActionState(createPost, {});
  return (
    <form action={formAction}>
      <input name="title" />
      {state.error && <p role="alert">{state.error}</p>}
      <button disabled={pending}>{pending ? "Saving..." : "Save"}</button>
    </form>
  );
}

Libraries such as Zod are popular for validation, which, like permission checks, must run inside the action on the server.

Client state

UI-only state, such as an open menu or the selected tab, belongs in useState or useReducer in Client Components. When several components share it, create a Context provider as a Client Component and wrap it around the tree in the root layout. The layout itself stays a Server Component.

// app/providers.tsx
"use client";

import { createContext, useContext, useState } from "react";

const ThemeContext = createContext<{ dark: boolean; toggle: () => void } | null>(null);

export function Providers({ children }: { children: React.ReactNode }) {
  const [dark, setDark] = useState(false);
  return <ThemeContext value={{ dark, toggle: () => setDark(!dark) }}>{children}</ThemeContext>;
}

export const useTheme = () => useContext(ThemeContext);

State worth sharing or bookmarking, such as a search query or sort order, is best kept in URL search params. Pages read it through the searchParams prop and Client Components through useSearchParams. For server data that updates frequently in the browser, SWR or TanStack Query work well, and libraries such as Zustand help with complex global state.

Summary

  • Read data in async Server Components and start independent requests together with Promise.all.
  • Caching defaults differ between versions, so confirm which model you use (fetch options or "use cache").
  • Use Route Handlers for APIs exposed to others and Server Actions for mutations inside your app.
  • Keep UI state in Client Components and shareable state in the URL.

0 条评论

热门评论最新优先

登录 · 登录后即可发表评论。