为什么不应该在 Sidebar 组件中直接使用 useSessions Hook
引言 在 React 开发中,我们经常面临一个重要的架构决策:是否应该让组件直接使用业务逻辑 hooks,还是通过 props 传递数据和回调函数?本文将通过一个实际的聊天应用案例,分析为什么建议保持组件的数据流清晰,而不是在组件中直接使用业务逻辑 hooks。 问题背景 在我们的聊天应用中,有一个 Sidebar 组件负责显示聊天会话列表。最初的设计是: // 当前架构:通过 props 传递数据 <Sidebar sessions={sessions} currentSessionId={currentSessionId} onSelectSession={selectSession} onNewSession={createNewSession} onDeleteSession={deleteSession} isOpen={sidebarOpen} onToggle={() => setSidebarOpen(!sidebarOpen)} /> 有人可能会问:为什么不直接在 Sidebar 组件中使用 useSessions hook 呢? // 不推荐的架构:直接在组件中使用 hook export function Sidebar() { const { sessions, currentSessionId, selectSession, createNewSession, deleteSession } = useSessions() // ... } 为什么不建议在组件中直接使用业务逻辑 Hooks? 1. 关注点分离 (Separation of Concerns) 组件应该专注于 UI 渲染,而不是业务逻辑 // ✅ 好的做法:纯展示组件 export function Sidebar({ sessions, onSelectSession, onNewSession, onDeleteSession }) { return ( <div> {sessions.map(session => ( <button key={session.id} onClick={() => onSelectSession(session.id)}> {session.title} </button> ))} </div> ) } // ❌ 不好的做法:组件混合了业务逻辑 export function Sidebar() { const { sessions, selectSession } = useSessions() // 业务逻辑混入组件 // ... } 2. 可测试性 (Testability) 纯组件更容易进行单元测试 ...