zoukankan      html  css  js  c++  java
  • [Recompose] Flatten a Prop using Recompose

    Learn how to use the ‘flattenProp’ higher order component to take a single object prop and spread each of its fields out as a prop.

    For example,we have a 'redux-react' like app:

    import React from 'react';
    import { withProps } from 'recompose';
    
    // Mock Configuration
    function ReactRedux() {
        const state = {
            name: 'Joe',
            status: 'active'
        };
        return {
            connect: (map) => withProps(map(state))
        };
    }
    
    const {connect} = ReactRedux();
    
    const UserStyle = {
        position: 'relative',
        background: 'lightblue',
        display: 'inline-block',
        padding: '10px',
        cursor: 'pointer',
        marginTop: '50px'
    };
    
    const mapStateToProps = (state) => ({
        name: state.name,
        status: state.status
    });
    
    let User4 = ({ status, name }) => (
        <div style={UserStyle}>
            {name} - {status}
        </div>
    );
    
    User4 = connect(mapStateToProps)(User4);
    
    export default User4;

    Here we using 'connect' & 'mapStateToProps'. 'connect' is also a HoC. 

    import React from 'react';
    import { withProps, compose, flattenProp } from 'recompose';
    
    // Mock Configuration
    function ReactRedux() {
        const state = {
           user: {
               name: 'Joo',
               status: 'inactive'
           },
           address: {
               street: 'SF',
               postcode: '10101'
           }
        };
        return {
            connect: (map) => withProps(map(state))
        };
    }
    
    const {connect} = ReactRedux();
    
    const UserStyle = {
        position: 'relative',
        background: 'lightblue',
        display: 'inline-block',
        padding: '10px',
        cursor: 'pointer',
        marginTop: '50px'
    };
    
    const mapStateToProps = (state) => ({
        user: state.user,
        address: state.address
    });
    
    const enhance = compose(
        connect(mapStateToProps),
        flattenProp('user')
    );
    
    let User4 = enhance(({ name, status, address }) => (
        <div style={UserStyle}>
            {name} - {status} - {address.street} - {address.postcode}
        </div>
    ));
    
    
    export default User4;

    'flattenPorp' helps to get single prop from object and spread its props.

  • 相关阅读:
    [转载]tlb、tlh和tli文件的关系
    [转载]美国不是中国唯一的榜样
    使用spring.net 1.3.2框架部署在虚拟目录上发生错误
    用Log4Net记录NHibernate中执行的SQL语句及执行时间
    IIS7/8 HTTP Error 500.19 错误 0x80070021
    IE下点击scrollbar会导致焦点移动到body
    性能测试学习(一)--基础知识点
    测试基础知识点汇总
    如何制定测试计划
    《软件测试经验与教训》摘录
  • 原文地址:https://www.cnblogs.com/Answer1215/p/6856495.html
Copyright © 2011-2022 走看看