不想每次用數(shù)據(jù)的時(shí)候?qū)憁apDispatchToProps嘀掸,mapStateToProps 等這些重復(fù)的代碼
關(guān)鍵代碼
import { connect } from 'react-redux'
import { bindActionCreators } from 'redux'
const _connect = function (Uicomponent, reducers = []) {
let mapStateToProps = (state) => {
let result = {}
// 如果沒(méi)有傳入reducer的名字叫榕,認(rèn)為都想要
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 = {}
// 如果沒(méi)有傳入reducer的名字馍佑,認(rèn)為都想要
if ( reducers.length <= 0 ) return {};
if ( !_connect.actions ) return {};
// 將對(duì)應(yīng)的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 代表一個(gè)數(shù)據(jù)模塊堆巧,暴露出的一個(gè)reducer叫main礁叔;
//組件牍颈。。琅关。Cal
export default connect(Cal,["main"])
//或
export default connect(Cal,[{name:'main',state:['count']}])
-
在組件中使用數(shù)據(jù)
action方法調(diào)用:this.props.main_action.younctionname
state中的數(shù)據(jù)的使用:
this.props.main.yourdataname
main模塊
import {combineReducers } from "redux";
import main from "./reducer"
//可以引入多個(gè)煮岁,起名不沖突即可
const reducer=combineReducers({
main
})
export default reducer;