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.

  • 相关阅读:
    手机号码 正则表达式
    邮政编码的正则表达式
    对象为null,调用非静态方法产生空指针异常
    文件找不到异常(FileNotFoundException)
    数组下标越界异常解决方法
    空指针异常的解决方法
    需求:打印九九乘法表
    创建简单线程
    ·博客作业06--图
    博客作业05--查找
  • 原文地址:https://www.cnblogs.com/Answer1215/p/6856495.html
Copyright © 2011-2022 走看看