ReactJS 设计模式 ~状态机模式~

发布: (2026年1月6日 GMT+8 08:01)
2 min read
原文: Dev.to

Source: Dev.to

概览

状态机模式有助于保持 React 代码库的可读性、可维护性和高效性。与其管理多个布尔状态变量,不如使用单个 status 变量来表示组件的状态,从而简化状态管理并防止出现不可能的组合(例如同时处于加载和错误状态)。

之前

function App() {
  const [error, setError] = useState(true);
  const [loading, setLoading] = useState(false);
  const [ready, setReady] = useState(false);

  const handleNextState = () => {
    if (status === "ready") {
      setLoading(true);
      setReady(false);
      setError(false);
    } else if (status === "loading") {
      setError(true);
      setReady(false);
      setLoading(false);
    } else if (status === "error") {
      setReady(true);
      setError(false);
      setLoading(false);
    }
  };

  return (
    
      
## State Machine Pattern

      Next State

      {loading && 
Loading...
}
      {error && 
Something went wrong!
}
      {ready && 
Ready to go!
}
    
  );
}

状态机模式

      Next State

      {loading && 
Loading...
}
      {error && 
Something went wrong!
}
      {ready && 
Ready to go!
}

之后

function App() {
  const [status, setStatus] = useState('ready');

  const handleNextState = () => {
    if (status === "ready") {
      setStatus("loading");
    } else if (status === "loading") {
      setStatus("error");
    } else if (status === "error") {
      setStatus("ready");
    }
  };

  return (
    
      
## State Machine Pattern

      Next State

      {status === "loading" && 
Loading...
}
      {status === "error" && 
Something went wrong!
}
      {status === "ready" && 
Ready to go!
}
    
  );
}
Back to Blog

相关文章

阅读更多 »

ReactJS 设计模式 ~状态共置~

Collocating State 是将状态放置在尽可能靠近其使用位置的做法。此模式降低了复杂性,使组件更易于理解。之前……