您好,欢迎来到二三娱乐。
搜索
您的当前位置:首页Redux的使用(2):redux-actions

Redux的使用(2):redux-actions

来源:二三娱乐

前言

redux-actions

这个库提供了5个模块,分别是createAction(s)handleAction(s)combineActions,这其中我经常用的是createAction与handleAction这两个模块

  1. handleAction
// 还是拿上一篇的代码做例子
import { handleAction } from 'redux-actions'
import { combineReducers } from 'redux'

// handleAction可以更加显式地将action与其相对应的处理函数连接起来
// 并且省去了之前的各种switch-case判断
// 其第三个参数则是该state的默认值
const num = handleAction('ADD', (state, action) => state + 2, 0)

// 与之前一样,放入combineReducers中做整合
const reducers = combineReducers({
  num
})

export default reducers
  1. createAction
// 还是拿上一篇的代码做例子
import React, { Component } from 'react'
import { connect } from 'react-redux'
import { createAction } from 'redux-actions'

class Son1 extends Component {
  render() {
    const { value, onIncreaseClick } = this.props

    return (
      <div>
        <div onClick={onIncreaseClick}>add</div>
        <p>{value}</p>
      </div>
    )
  }
}

const mapStateToProps = state => {
  return {
    value: state.num
  }
}
// 在这里我们向createAction方法传入action的名字,在函数内部,帮我们进行了action的相关处理
const add = createAction('ADD')
const mapDispatchToProps = dispatch => {
  return {
    // dispatch直接调用add的返回值就可以了
    onIncreaseClick: () => dispatch(add())
  }
}

const reduxSon1 = connect(
  mapStateToProps,
  mapDispatchToProps
)(Son1)

export default reduxSon1

Copyright © 2019- yule263.com 版权所有 湘ICP备2023023988号-1

违法及侵权请联系:TEL:199 1889 7713 E-MAIL:2724546146@qq.com

本站由北京市万商天勤律师事务所王兴未律师提供法律服务