[Recompose] Add Lifecycle Hooks to a Functional Stateless Component using Recompose

Learn how to use the 'lifecycle' higher-order component to conveniently use hooks without using a class component.

 

复制代码
import React from 'react';
import { withReducer, withHandlers, compose, lifecycle } from 'recompose';

// Mock Configuration
function fetchConfiguration() {
    return new Promise((resolve) => {
        setTimeout(() => resolve({
                                     showStatus: true,
                                     canDeleteUsers: true
                                 }), 300);
    });
}
const withConfig = lifecycle({
                                 getInitialState(){
                                     return { config: {} };
                                 },
                                 componentDidMount() {
                                     fetchConfiguration()
                                         .then((config) => {
                                             this.setState({ config })
                                         })
                                 }
                             })

const UserStyle = {
    position: 'relative',
    background: 'lightblue',
    display: 'inline-block',
    padding: '10px',
    cursor: 'pointer',
    marginTop: '50px'
};

const StatusListStyle = {
    background: '#eee',
    padding: '5px',
    margin: '5px 0'
};

const TooltipStyle = {
    fontSize: '10px',
    position: 'absolute',
    top: '-10px',
    width: '80px',
    background: '#666',
    color: 'white',
    textAlign: 'center'
};

const StatusList = () =>
    <div style={StatusListStyle}>
        <div>pending</div>
        <div>inactive</div>
        <div>active</div>
    </div>;

const withToggle = compose(
    withReducer('toggleState', 'dispatch', (state = false, action) => {
        switch( action.type ) {
            case 'SHOW':
                return true;
            case 'HIDE':
                return false;
            case 'TOGGLE':
                return !state;
            default:
                return state;
        }
    }, false),
    withHandlers({
                     toggle: ({ dispatch }) => (e) => dispatch({ type: 'TOGGLE' }),
                     show: ({ dispatch }) => (e) => dispatch({ type: 'SHOW' }),
                     hide: ({ dispatch }) => (e) => dispatch({ type: 'HIDE' })
                 })
);

const Statue = withToggle(
    ({ status, toggle, toggleState }) =>
        (<span onClick={() => toggle(!toggleState)}>
            {status}
            {toggleState && <StatusList/>}
        </span>)
);

const Tooltip = withToggle(({ show, hide, toggleState, text, children }) => (
    <span>
        <span>
            {toggleState && <div
                style={TooltipStyle}>
                { text }
            </div>}
            <span
                onMouseOver={show}
                onMouseOut={hide}
            >
                { children }
            </span>
        </span>
    </span>
));

const User3 = withConfig(({ status, name, config }) => (
    <div style={UserStyle}>
        <Tooltip text="Cool Dude!">{name}</Tooltip>-
        {config.showStatus && <Statue status={status}/>}
        {config.canDeleteUsers && <button>X</button>  }
    </div>
));

export default User3;
复制代码

 

posted @   Zhentiw  阅读(386)  评论(0编辑  收藏  举报
编辑推荐:
· 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-15 [PWA] 4. Hijacking Request
2016-05-15 [PWA] 3. Devtool
2016-05-15 [PWA] 2. Service worker life cycle
2016-05-15 [PWA] 1. Intro to Service worker
2016-05-15 [PWA] 0. Introduce to Offline First
2016-05-15 [Firebase] Deploy you website to Firebase
2015-05-15 [AngularJS] Error: $location:nobase
点击右上角即可分享
微信分享提示