ReactJS 设计模式 ~Guard Clause Rendering~
发布: (2026年2月6日 GMT+8 15:11)
1 min read
原文: Dev.to
Source: Dev.to
概述
此模式在组件的 render 函数开头使用提前返回(early return)语句来处理边缘情况、加载状态或无效数据。通过对这些条件提前返回,主要的 JSX 返回语句保持简洁平坦,从而提升可读性和可维护性。
示例
import { useState } from "react";
function Loading() {
return
Loading...
;
}
function Error() {
return
Error!
;
}
function UserProfile({ loading, error, user }) {
if (loading) return ;
if (error) return ;
return (
## {user.name}
{user.email}
{user.role}
);
}
function App() {
const [loading, setLoading] = useState(true);
const [error, setError] = useState(false);
const user = {
name: "John Doe",
email: "Sample@example.com",
role: "Software Developer",
};
return (
setLoading(!loading)}>Toggle Loading
setError(!error)}>Toggle Error
);
}
export default App;