before

  1. // actionTypes.js
  2. const BOOK_LIST_GET = 'BOOK_LIST_GET';
  3. const BOOK_DELETE = 'BOOK_DELETE';
  4. export default {
  5. /**
  6. * 获取书籍列表
  7. */
  8. BOOK_LIST_GET,
  9. /**
  10. * 删除书籍
  11. */
  12. BOOK_DELETE,
  13. };
  14. // reducer.js
  15. import actionTypes from './actionTypes';
  16. const initialState = {
  17. bookList: [],
  18. };
  19. const pageMainReducer = (state = initialState, action) => {
  20. switch (action.type) {
  21. case actionTypes.BOOK_LIST_GET:
  22. return {
  23. ...state,
  24. bookList: action.bookList,
  25. };
  26. default:
  27. return state;
  28. }
  29. };
  30. export default pageMainReducer;

after

  1. import { createActions, handleActions, combineActions } from 'redux-actions';
  2. const defaultState = { counter: 10 };
  3. const { increment, decrement } = createActions({
  4. INCREMENT: (amount = 1) => ({ amount }),
  5. DECREMENT: (amount = 1) => ({ amount: -amount })
  6. });
  7. // increment(); // { type: 'INCREMENT' }
  8. // decrement(); // { type: 'DECREMENT' }
  9. const reducer = handleActions(
  10. {
  11. [combineActions(increment, decrement)]: (
  12. state,
  13. { payload: { amount } }
  14. ) => {
  15. return { ...state, counter: state.counter + amount };
  16. }
  17. },
  18. defaultState
  19. );
  20. export default reducer;

createAction

  1. import { createActions } from 'redux-actions';
  2. import actionTypes from './actionTypes';
  3. export default createActions({
  4. [actionTypes.BOOK_LIST_GET]: () => {
  5. const bookList = [{
  6. id: '1',
  7. title: '123',
  8. description: '123',
  9. }, {
  10. id: '2',
  11. title: '234',
  12. description: '234',
  13. }];
  14. return bookList;
  15. },
  16. [actionTypes.BOOK_DELETE]: (id) => {
  17. console.info(`删除id${id}的Book`);
  18. return { id };
  19. },
  20. });

**

handleAction

  1. import { handleActions } from 'redux-actions';
  2. import actionTypes from './actionTypes';
  3. const initialState = {
  4. bookList: [],
  5. };
  6. const pageMainReducer = handleActions({
  7. [actionTypes.BOOK_LIST_GET]: (state, action) => {
  8. return {
  9. ...state,
  10. bookList: action.payload,
  11. };
  12. },
  13. [actionTypes.BOOK_DELETE]: (state, action) => {
  14. return {
  15. ...state,
  16. bookList: state.bookList.filter(l => l.id !== action.payload.id),
  17. };
  18. },
  19. }, initialState);
  20. export default pageMainReducer;

ref

https://www.jianshu.com/p/d2615a7d725e

https://redux-actions.js.org/
**