React 19 正式到来
React 19 是近年来最重要的版本更新,带来了多项改变游戏规则的新特性。
Actions(动作)
Actions 是 React 19 最核心的新概念——它让异步状态管理变得前所未有的简单:
"use client";
function SubmitButton() {
// useActionState 管理表单提交状态
const [state, action, pending] = useActionState(
async (prev, formData) => {
const name = formData.get("name");
const res = await fetch("/api/users", {
method: "POST",
body: JSON.stringify({ name }),
});
return { success: true, id: (await res.json()).id };
},
{ success: false, id: null }
);
return (
<form action={action}>
<input name="name" required disabled={pending} />
<button type="submit" disabled={pending}>
{pending ? "提交中..." : "提交"}
</button>
{state.success && <p>创建成功 ID: {state.id}</p>}
</form>
);
}
use Hook
可以直接在组件中读取 Promise 和 Context:
function Comments({ promise }) {
const comments = use(promise); // 直接 resolve Promise
return comments.map(c => <p key={c.id}>{c.text}</p>);
}
ref 作为 prop
不再需要 forwardRef:
function Input({ ref, ...props }) {
return <input ref={ref} {...props} />;
}
React 19 标志着 React 进入了新的时代——服务端组件成熟、Actions 简化开发、API 更加直观。