使用redux-actions优化actions管理

简介

redux 相关知识参考:Redux基本使用

为了定义 redux 里面的 action,我们可能需要写 actions.jsactionTypes.js 等文件

redux-actions 简化了 action 的编写

安装:npm i redux-actions --save

具体使用

  • 修改 src/store/actions.js 文件
import { createActions } from 'redux-actions'

export default createActions({
  APP: {
    ADD_TODO: undefined,
    TOGGLE_TODO: undefined,
    SET_FILTER: undefined,
  },
  USER: {
    LOGIN: undefined,
    LOGOUT: undefined,
    SET_USER_ROLE: undefined,
  },
})
  • 删除 src/store/actionType.js 文件

  • 修改 reducer 文件,比如: src/store/reducers/todos.js 文件

import { handleActions } from 'redux-actions'
import Actions from '../actions'

// state的初始值
const initialState = {
  allIds: [],
  byIds: {}
}

export default handleActions({
  [Actions.app.addTodo](state, { payload }) {
    const { id, content } = payload
    return {
      // 用这种展开的语法,不去修改原始值,而是直接返回一个新值
      allIds: [...state.allIds, id],
      byIds: {
        ...state.byIds,
        [id]: {
          content,
          completed: false
        }
      }
    }
  },
  [Actions.app.toggleTodo](state, { payload }) {
    const { id } = payload
    return {
      ...state,
      byIds: {
        ...state.byIds,
        [id]: {
          ...state.byIds[id],
          completed: !state.byIds[id].completed
        }
      }
    }
  },
}, initialState)
  • 修改 src/store/index.js 文件,添加 actions 导出
// ...
export { default as Actions } from './actions'
  • 使用示例
import { useSelector, useDispatch } from 'react-redux'
import Actions from '@/store/actions'

export default function Demo(props) {
  const app = useSelector(({ app }) => app)
  const dispatch = useDispatch()

  const onTodoClick = id => {
    dispatch(Actions.app.toggleTodo({ id }))
  }
  // ...
}

你可能感兴趣的:(使用redux-actions优化actions管理)