1.0.0 • Published 4 years ago

zend-redux v1.0.0

Weekly downloads
-
License
ISC
Repository
-
Last release
4 years ago

zend-redux

基于react-redux封装,让项目目录更加清晰

安装

yarn add zend-redux 或 npm i zend-redux -S 

使用

在store 入口文件使用

import {
    createStore,
    combineReducers,
    applyMiddleware,
    compose,
  } from 'redux';
import zendRedux, { thunk } from 'zend-redux';
import app from './app'; // app模块

const reducers = zendRedux({
  app,
  // 其他模块...
});

// 开发环境下使用 redux 浏览器插件
const composeEnhancers = process.env.NODE_ENV === 'development' && 
  window.__REDUX_DEVTOOLS_EXTENSION_COMPOSE__ || 
  compose;

export default createStore(
  combineReducers(reducers),
  composeEnhancers(applyMiddleware(thunk)),
);

模块说明

每个模块必须包含namespace属性,完整属性如下app模块:

export default {
  namespaces: 'app',
  state: {
    test: 123,
    count: 0
  },
  reducers: {
    setTest(state, payload) {
      return { // 无需返回整个state的数据,使用了扩展符浅合并
        test: payload
      };
    },
    setCount(state, payload) {
      return {
        count: payload
      }
    } 
  },
  actions: { // 异步处理
    /**
     * put {Function} 用于提交reducers,接受一个对象,对象包含type和payload属性
     * state {Object} 当前模块的state
     * dispatch {Function} react-redux的dispatch
     */
    async changeCount({ put,  state, dispatch }, payload) {
      // 异步处理
      window.setTimeout(() => {
        put({
          type: 'setCount',
          payload
        });
      }, 2000)
    }
  },
  getters: { // 获取某属性,类似vuex的getters
     test: state => state.test
  }
};

API

属性说明类型
thunk支持异步处理的中间件,参考redux-thunk 实现function
useZendGetters调用某模块的getter,获取其返回值function(namespace, 'test', // 其他... )
useZendReducers调用reducersfunction(namespace, 'test', // 其他... )
useZendActions调用actionsfunction(namespace, 'test', // 其他... )

目录结构

├── src                                        
│   ├── store                                   
│   │   ├── app         // app模块                          
│   │   ├── system      // 系统管理模块                                             
│   │   └── index.js    // 入口文件              
.