绑定action的创建者
1.为什么要实现这个api?
开发者为了在使用中书写简便,可以统一管理actions,减少错误率
let add = (number) => {
return { type: 'ADD', payload: number }
}
let minus = () => {
return { type: 'MINUS' }
}
let actions = {
add: (number) => {
return { type: 'ADD', payload: number }
},
minus: () => {
return { type: 'MINUS' }
}
}
<button onClick={() => actions.add(5)}>+</button>
<button onClick={minus}>-</button>
{/* <button onClick={() => store.dispatch(add())}>+</button>
<button onClick={() => store.dispatch(minus())}>-</button> */}
export default function bindActionCreators(actionCreators, dispatch) {
function bindActionCreator(actionCreator) {
// dispatch(actionCreator())
return (...args) => dispatch(actionCreator(...args))
}
if (typeof actionCreators === 'function') {
return bindActionCreator(actionCreators, dispatch)
}
const boundActionCreators = {};
for (let key in actionCreators) {
boundActionCreators[key] = bindActionCreator(actionCreators[key], dispatch)
}
return boundActionCreators
}
/**
* let add = (number) => {
return { type: 'ADD', payload: number }
}
let minus = () => {
return { type: 'MINUS' }
}
let actions = {
add: (number) => {
return { type: 'ADD', payload: number }
},
minus: () => {
return { type: 'MINUS' }
}
}
*/