bindActionCreators 的作用和原理

发布于 2022-09-14 13:24:22 字数 2499 浏览 148 评论 0

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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。
列表为空,暂无数据

关于作者

陌路终见情

暂无简介

文章
评论
27 人气
更多

推荐作者

櫻之舞

文章 0 评论 0

弥枳

文章 0 评论 0

m2429

文章 0 评论 0

野却迷人

文章 0 评论 0

我怀念的。

文章 0 评论 0

    我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
    原文