ReactJS 设计模式 ~Guard Clause Rendering~

发布: (2026年2月6日 GMT+8 15:11)
1 分钟阅读
原文: 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;
Back to Blog

相关文章

阅读更多 »

Go 的秘密生活:'defer' 语句

第20章:堆叠的牌组 Ethan的桌面PC风扇嗡嗡作响,声音很大。他盯着一个终端,终端像失控的火焰一样不断喷出错误信息……