react-redux中的connect的小封装

为了实现connect更方便的应用,所以就简单的封装了一下,使用方法:

export default connect(MessageControl,[{name:'message',state:['message']}])
export default connect(MessageControl,['message'])

接下来是封装的代码

import {connect} from 'react-redux'
import {bindActionCreators} from 'redux'
import action from './actionCreators'
const _connect = (UiComponent,reducers = []) => {
    
    let mapStateToProps = (state) => {
        let result = {}
        // 如果没有传值,那么将所有的东西都传过去
        if(reducers.length <=0) return state
        reducers.forEach(reducers => { //遍历传的redusers
            if(typeof reducers === 'string'){ // 假设传的是一个字符串
                result[reducers] = state[reducers] ? state[reducers] : {}
             }else if(typeof reducers === 'object') { // 假设传入的是一个对象
                result[reducers.name] = filterObject(state[reducers.name],reducers.states)
            }
        })
        // return {
        //     reducers:state.reducers
        // }
        return result
    }
    
    let mapDispatchToProps = (dispatch) => {
        let result = {}
        // 如果没有传值,那么什么方法都不给他
        if(reducers.length <=0) return {}

        // 将对应的actionCreator的方法处理后传给UI组件
        reducers.forEach(reducers => { //遍历传的redusers
            let name = (typeof reducers === 'string') ? reducers : reducers.name
            result[name+'_actions'] = bindActionCreators(action[name],dispatch)
            // [name+'_actions'] 字符串可以随便放
        })
        return result
    }

    return connect(mapStateToProps,mapDispatchToProps)(UiComponent)
}

function filterObject (obj, arr) {
    if ( !arr || arr.length <= 0 ) return obj;
    let result = {}
    arr.forEach(key => {
        if ( obj.hasOwnProperty(key) ) {
            result[key] = obj[key]
        }     
    })
    return result
}

export default _connect

我们还需要一个文件用来存放reduser的一些方法,建一个actionCreators的文件,代码如下:

import count from '../promise/store/count/action-creators'
import message from '../promise/store/message/action-creators'

export default {
    count,
    message,
}

这样简单封装就完成了,然后就可以引入使用了

你可能感兴趣的:(react)