redux-actions(扩展)
一、下载
yarn add redux-actions
npm i redux-actions
二、使用
1、创建 action 对象的函数
基础语法
import { createAction } from 'redux-actions';
const 返回action对象的函数 = createAction(action 的 type 值);
案例代码:
import types from './actionTypes.js'
import { createAction } from 'redux-actions';
export const doneChangeAction = createAction(types.DONE_CHANGE);
export const addTodosAction = createAction(types.ADD_TODOS);
export const currentChangeAction = createAction(types.CURRENT_CHANGE);
2、创建 reducer 函数
基础语法
import { handleActions } from 'redux-actions'
handleActions({
[type值]: (state, action) => { return 要修改的新值 }
}, 数据初始值)
代码案例
import { handleActions } from 'redux-actions'
const todoListReducer = handleActions({
[types.DONE_CHANGE]: (state, { payload }) => ({
...state,
todos: state.todos.map(item => {
if (item.id === payload) {
return {
...item,
done: !item.done
}
}
return item;
})
}),
[types.ADD_TODOS]: (state, { payload }) => ({
...state,
todos: [
...state.todos,
{
id: state.newId,
value: payload,
done: false
}
],
newId: state.newId + 1
}),
[types.CURRENT_CHANGE]: (state, { payload }) => ({
...state,
current: payload
})
}, initState);