bindActionCreators 的作用和原理
const initState = {number: 0} function reducer (state=initState, action) { switch (action.type) { case 'INCREMENT': return {number: state.number + 1} case 'DECREMENT1': return {number: state.number - 1} default: return state } }
组件代码
import store from './store' // 导入的store import actions from './store/counter' // 导入的actions class App extends Component { constructor(props) { super(props); this.state = { number: 0 } } componentDidMount() { this.subscribe = store.subscribe(() => { this.setState({number: store.getState().number}) }) } handleClick = () => { store.dispatch(actions.increment()) // 通过dispatch传入increment方法的执行结果 } render() { return ( <div> <p>{this.state.number}</p> <button onClick={this.handleClick}>+</button> </div> ); } }
使用之后
import store from './store' import actions from './store/counter' import { bindActionCreators } from 'redux' let newAction = bindActionCreators(actions, store.dispatch) class App extends Component { constructor(props) { super(props); this.state = { number: 0 } } componentDidMount() { this.subscribe = store.subscribe(() => { this.setState({number: store.getState().number}) }) } handleClick = () => { newAction.increment() // 直接调用方法 } render() { return ( <div> <p>{this.state.number}</p> <button onClick={this.handleClick}>+</button> </div> ); } }
实现原理
function bindActionCreator(actionCreator, dispatch) { return (...args) => dispatch(actionCreator(...args)) } export default function bindActionCreators(actionCreators, dispatch) { // actionCreators是函数 if (typeof actionCreator === 'function') { return bindActionCreator(actionCreators, dispatch) } // actionCreators不是对象会报错 if (typeof actionCreators !== 'object' || actionCreators === null) { throw new Error('actionCreators期望是一个对象或者一个函数') } const keys = Object.keys(actionCreators) const boundActionCreators = {} // 循环对象的属性名 for (let i = 0; i < keys.length; i++) { const key = keys[i] const actionCreator = actionCreators[key] if (typeof actionCreator === 'function') { boundActionCreators[key] = bindActionCreator(actionCreator, dispatch) } } return boundActionCreators }
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论