[Recompose] Replace a Component with Non-Optimal States using Recompose
Learn how to use the ‘branch’ and ‘renderComponent’ higher-order components to show errors or messaging when your component is in a non-optimal state. Avoid putting extraneous logic to show errors or messaging into your core component by organizing your non-optimal states into custom higher-order components.
import React from 'react'; import { lifecycle, branch, compose, renderComponent } from 'recompose'; const User = ({ name, status }) => <div className="User">{ name }—{ status }</div>; const withUserData = lifecycle({ componentDidMount() { fetchData().then( (users) => this.setState({ users }), (error) => this.setState({ error }) ); } }); const UNAUTHENTICATED = 401; const UNAUTHORIZED = 403; const errorMsgs = { [UNAUTHENTICATED]: 'Not Authenticated!', [UNAUTHORIZED]: 'Not Authorized!', }; const AuthError = ({ error }) => error.statusCode && <div className="Error">{ errorMsgs[error.statusCode] }</div>; const NoUsersMessage = () => <div>There are no users to display</div>; // Mock Service const noUsers = []; const users = [ { name: "Tim", status: "active" }, { name: "Bob", status: "active" }, { name: "Joe", status: "inactive" }, { name: "Jim", status: "pending" }, ]; function fetchData() { return new Promise((resolve, reject) => { setTimeout(() => { // reject({ statusCode: UNAUTHENTICATED }); // reject({ statusCode: UNAUTHORIZED }) // resolve(noUsers); resolve(users); }, 100); }); } const hasError = ({error}) => error && error.statusCode; const hasNoUser = ({users}) => users && users.length === 0; const enhance = compose( withUserData, branch(hasError, renderComponent(AuthError)), branch(hasNoUser, renderComponent(NoUsersMessage)), ); const User6 = enhance(({users}) => ( <div className="UserList"> { users && users.map((user) => <User {...user} />) } </div> )); export default User6;
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· SQL Server 2025 AI相关能力初探
· Linux系列:如何用 C#调用 C方法造成内存泄露
· AI与.NET技术实操系列(二):开始使用ML.NET
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· Manus重磅发布:全球首款通用AI代理技术深度解析与实战指南
· 开源Multi-agent AI智能体框架aevatar.ai,欢迎大家贡献代码
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· AI技术革命,工作效率10个最佳AI工具
2016-05-16 [PWA] 8.Unobtrusive update: Delete old cache and only keep one, hard refresh to let new SW to take control
2016-05-16 [PWA] 7. First Cache when installed
2016-05-16 [PWA] 6. Hijacking response
2016-05-16 [Javascript] Using console.count to Count Events
2016-05-16 [Javascript] Proper use of console.assert in JavaScript
2016-05-16 [Javascript] Grouping and Nesting Console Log Output
2016-05-16 [PWA] 5. Hijacking one type of request