美文网首页React
Redux的使用(2):redux-actions

Redux的使用(2):redux-actions

作者: e93a88ffeabd | 来源:发表于2018-03-06 16:22 被阅读19次

前言

上次写了一篇redux的使用(1):react-redux,这只是在学习redux道路上的一个开始。随着学习的深入,发现react的生态圈实在是丰盛,各种库、插件层出不穷,并且质量都非常高,今天来接触下使用程度很高的一个redux库: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

相关文章

网友评论

    本文标题:Redux的使用(2):redux-actions

    本文链接:https://www.haomeiwen.com/subject/nocrfftx.html