为什么不应该在 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) 纯组件更容易进行单元测试 ...

八月 21, 2025

减少 Tailwind 中重复和冗长的 className

有几种方法可以减少 Tailwind 中重复和冗长的 className: 1. 使用 @apply 语法 在自定义的 CSS 文件中,使用 Tailwind 的 @apply 语法将常用的样式组合成一个自定义的类。例如: /* styles.css */ .btn-primary { @apply bg-blue-500 text-white py-2 px-4 rounded; } 然后在组件中使用: <button className="btn-primary">Click me</button> 这样可以减少 JSX 文件中的 className 冗余。 2. 封装组件 将常用的样式封装成可复用的组件。例如,将按钮样式封装为一个 Button 组件: const Button = ({ children, className, ...props }) => ( <button className={`bg-blue-500 text-white py-2 px-4 rounded ${className}`} {...props} > {children} </button> ); // 使用 <Button className="my-2">Click me</Button>; 通过这种方式,可以保持代码的简洁并提高复用性。 3. 使用 clsx 或 classnames 库 这些库可以帮助你有条件地组合多个 className,减少重复性。例如: ...

十月 23, 2024

Err Ossl Evp Unsupported

一个比较老的Vue项目,在启动时候,报错: opensslErrorStack: [ 'error:03000086:digital envelope routines::initialization error' ], library: 'digital envelope routines', reason: 'unsupported', code: 'ERR_OSSL_EVP_UNSUPPORTED' 问题原因是nodejs升级到17后,openssl3.0 对允许算法密钥大小增加了严格的限制,临时的解决办法是配置node_options. # Windows 环境 $env:NODE_OPTIONS="--openssl-legacy-provider" #or set NODE_OPTIONS=--openssl-legacy-provider # Linux or Mac export NODE_OPTIONS=--openssl-legacy-provider 上述的方法是一次性的,也可以在package.json中对script进行修改,如 ... "serve" : "SET NODE_OPTIONS=--openssl-legacy-provider && vue-cli-service serve" ...

八月 22, 2023