// npm install --save redux-actions
1:作用:
当我们的在开发大型应用的时候,对于大量的action,我们的reducer需要些大量的swich来对action.type进行判断。
redux-actions可以简化这一烦琐的过程,它可以是actionCreator,也可以用来生成reducer,
其作用都是用来简化action、reducer。
主要函数有createAction、createActions、handleAction、handleActions、combineActions。
createAction
原来创建:
export const getCeshi = options => {
return {
type: [MINE],
payload: request(services.data),
}
}
现在:
import { createActions } from 'redux-actions'
import { MINE, MINE2 } from '@/constants'
export const getMine = createActions({
[MINE]: options => options,
[MINE2]: options => options,
// [MINE]: options => request(services.data) // services 文件夹的接口
})
handleActions
作用:redux框架下的reducer操作state,主要使用switch或if else来匹配
原来reducer操作state写法要使用switch或if else来匹配:
原来:
export default function (state = defaultState, action) {
switch (action.type) {
case 'LODING':
return { ...state, loading: action.payload }
case 'CESHI':
return { ...state, result: action.payload }
default:
return state
}
}
现在:
import { handleActions } from 'redux-actions'
import { MINE, MINE2 } from '@/constants'
const mineState = {
data: [],
data2: '',
}
export default handleActions({
[MINE]: (state, action) => ({ ...state, data: action.payload }) ,
[MINE2]: (state, action) => ({ ...state, data2: action.payload }) ,
}, mineState)
// handleAction可以更加显式地将action与其相对应的处理函数连接起来
// 并且省去了之前的各种switch-case判断
// 其第三个参数则是该state的默认值
// const num = handleAction('ADD', (state, action) => state + 2, 0)
页面中使用:
import React, { PureComponent } from 'react';
import './styles.less'
import { connect } from 'react-redux'
import { getMine } from '@/action/mine'
import { MINE, MINE2 } from '@/constants' // 常量
import { hump } from '@/utils/string' // 引用utils里的方法转换
export default @connect(state => {
console.log(state, 'state');
return {}
}, {
getMine: getMine[hump(MINE)],
})
class extends PureComponent {
fn = () => {
this.props.getMine('7777777777777')
}
render() {
return(
<div className='home-mine'>
<button onClick={this.fn}>点击redux-actions</button>
</div>
)
}
}
utils / string.js
export const hump = sName => {
return sName.toLowerCase().replace(/^\_/, '').replace(/\_([a-zA-Z0-9])([a-zA-Z0-9]+)/g, function(a, b, c){
return b.toUpperCase() + c.toLowerCase()
})
}
来源:CSDN
作者:辅助辅助助辅
链接:https://blog.csdn.net/qq_40924034/article/details/103843047