不想每次用数据的时候写mapDispatchToProps,mapStateToProps 等这些重复的代码
关键代码
import { connect } from 'react-redux'
import { bindActionCreators } from 'redux'
const _connect = function (Uicomponent, reducers = []) {
let mapStateToProps = (state) => {
let result = {}
// 如果没有传入reducer的名字,认为都想要
if ( reducers.length <= 0 ) return state;
reducers.forEach(reducer => {
if (typeof reducer === 'string') {
result[reducer] = state[reducer] ? state[reducer] : {}
} else { // obj
result[reducer.name] = filterObject(state[reducer.name], reducer.states)
}
})
return result
}
let mapDispatchToProps = (dispatch) => {
let result = {}
// 如果没有传入reducer的名字,认为都想要
if ( reducers.length <= 0 ) return {};
if ( !_connect.actions ) return {};
// 将对应的actionCreator的方法处理后传给UI组件
reducers.forEach(reducer => {
let name = (typeof reducer === 'string') ? reducer : reducer.name
if ( !_connect.actions[name] ) return false;
result[name + '_actions'] = bindActionCreators(_connect.actions[name], dispatch)
})
return result
}
return connect(mapStateToProps, mapDispatchToProps)(Uicomponent)
}
_connect.configActionCreators = function (actions) {
_connect.actions = actions
}
_connect.addActionCreator = function (actionCreator) {
_connect.actions = { ...(_connect.actions || {}), ...actionCreator }
}
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
使用:
-
安装
cnpm install react-redux-connect-lili -S
-
包的使用
import {Provider} from " react-redux-connect-lili" import {connect} from " react-redux-connect-lili" //同react-redux引入方法一样;
在引入connect的文件或者App.js文件里面添加你的action:如下:
import createAction from "../store/createActions"
connect.addActionCreator({
main: createAction
})
// main 代表一个数据模块,暴露出的一个reducer叫main;
//组件。。。Cal
export default connect(Cal,["main"])
//或
export default connect(Cal,[{name:'main',state:['count']}])
-
在组件中使用数据
action方法调用:this.props.main_action.younctionname
state中的数据的使用:
this.props.main.yourdataname
main模块
import {combineReducers } from "redux";
import main from "./reducer"
//可以引入多个,起名不冲突即可
const reducer=combineReducers({
main
})
export default reducer;
网友评论