React 19 已經到來,帶來了令人興奮的新功能和改進!
你好,開發者,我是Md Taqui Imam , React 19現在已經穩定,讓我們探索一下新功能以及如何在專案中使用這些功能。
本指南將透過實際範例引導您完成最重要的更新。
操作是 React 19 中最大的新增功能之一。
function UpdateProfile() {
const [error, submitAction, isPending] = useActionState(
async (previousState, formData) => {
const name = formData.get("name");
try {
await updateProfile(name);
return null; // No error
} catch (err) {
return "Failed to update profile";
}
},
null
);
return (
<form action={submitAction}>
<input type="text" name="name" />
<button type="submit" disabled={isPending}>
{isPending ? "Updating…" : "Update Profile"}
</button>
{error && <p className="error">{error}</p>}
</form>
);
}
新的useFormStatus
掛鉤可以輕鬆顯示載入狀態:
import { useFormStatus } from 'react-dom';
function SubmitButton() {
const { pending } = useFormStatus();
return (
<button disabled={pending}>
{pending ? 'Submitting…' : 'Submit'}
</button>
);
}
1.使用樂觀🆕
此掛鉤有助於在等待伺服器回應時建立即時回饋:
import { use } from 'react';
function UserProfile({ userPromise }) {
const user = use(userPromise);
return (
<div>
<h1>{user.name}</h1>
<p>{user.email}</p>
</div>
);
}
React 19 現在原生支援元資料標籤:
function BlogPost({ post }) {
return (
<article>
<title>{post.title}</title>
<meta name="description" content={post.summary} />
<link rel="canonical" href={post.url} />
<h1>{post.title}</h1>
<p>{post.content}</p>
</article>
);
}
用於優化資源加載的新 API:
import { preload, preinit, preconnect } from 'react-dom';
function App() {
// Preload important resources
preload('/fonts/main.woff2', { as: 'font' });
preinit('/styles/critical.css', { as: 'style' });
preconnect('https://api.example.com');
return <Main />;
}
Web 元件支援
React 19 現在完全支援自訂元素:
function App() {
return (
<div>
<custom-element
stringProp="hello"
numberProp={42}
objectProp={{ foo: 'bar' }}
onCustomEvent={(e) => console.log(e.detail)}
/>
</div>
);
}
參考作為道具
// Old way with forwardRef
const OldInput = forwardRef((props, ref) => (
<input ref={ref} {…props} />
));
// New way in React 19
function NewInput({ ref, …props }) {
return <input ref={ref} {…props} />;
}
更好的錯誤報告 🔥
React 19 提供了更清晰的錯誤訊息和更好的水合錯誤報告:
const root = createRoot(container, {
onCaughtError: (error) => {
// Handle errors caught by Error Boundaries
logError(error);
},
onUncaughtError: (error) => {
// Handle errors not caught by Error Boundaries
reportFatalError(error);
}
});
React 19 帶來了許多令人興奮的功能,使開發變得更容易、更有效率。新的表單處理功能、掛鉤和改進的資源載入將幫助開發人員用更少的程式碼建立更好的應用程式。
請記住,雖然這些功能現在很穩定,但建議在將現有應用程式升級到 React 19 時進行徹底測試。
有關更多訊息,請查看官方 React 19 公告和文件。
我們下一篇文章見,再見,拜伊,祝你有個愉快的一天。
{% 嵌入 https://dev.to/random\_ti %}
原文出處:https://dev.to/random_ti/react-19-is-now-stable-whats-new-1k3b