Redux 状态树设计探索

DTUX – 前端开发-小威

知识回顾

状态是指,Web应用中需要共享和通信的数据对象。状态管理是指用一种通用且合理的方式来组织维护这些状态。

 状态管理(State Management)

状态分类

 Domain data

    源于服务端对领域模型的抽象,比如user、projects

 UI State

    描述UI组件的展示状态,例如visible, selected

 App State

    例如应用的router信息,http请求状态等

规划原则

  • 按Domain Data划分
  • 按组件划分
  • 根据依赖关系
  • 深度不要过高
状态树分治
// reducerA.js

export const reducerA = (state = '', action) => {
    switch(action.type) {
        case "GET":
            return action.data
        default:
            return state
    }
}
// reducerB.js

export const reducerB = (state = '', action) => {
    switch(action.type) {
        case "GET":
            return action.data
        default:
            return state
            break;
    }
}
// mainReducer.js

import { combineReducers } from 'redux';

import { reducerA } from './reducerA'
import { reducerB } from './reducerB'

export const mainReducer = combineReducers({
    reducerB,
    reducerB,
})

看个栗子

RDOS的状态树

重新规划

Lorem ipsum dolor sit amet, consectetur adipiscing elit. Morbi nec metus justo. Aliquam erat volutpat.

| - state
    | - routing
    | - req
    | - user
    | - projects
    | - projectUsers
    | - realtimeTask
        | - tabs
        | - taskTree
        | - resourceTree
        | - currentTab
    | - offlineTask
        | - taskTree
        | - resourceTree
        | - functionTree
        | - sysFunctionTree
        | - workbenchTree
        | - dataSync
    | - sqlEditor
    | - comm
        | - visibleTask
        | - visibleCata
        | - ...

目录规划

Subtitle

| - reducers.js
| - modules
    | - comm
        | - req.js
        | - visible.js
    | - realTimeTask
        | - index.js
        | - tabs.js
        | - taskTree.js
        | - resourceTree.js
        | - currentTab.js
    | - offlineTask
        | - index.js
        | - taskTree
        | - resourceTree
        | - functionTree
        | - sysFunctionTree
        | - workbenchTree
        | - dataSync
        | - sqlEditor.js
    | - user.js
    | - projects.js
    | - projectUsers.js
    | - ...

总结

状态树的设计关系到后期代码的扩展,和维护问题。并且对于一个强迫症来说,逻辑混乱的数据结构是不能容忍的。

End

解决的问题

  • 组件间的数据共享和通信
  • 重复的API请求
  • 杂乱的状态维护逻辑
  • ...

Redux

Redux 状态树设计探索

By Ziv 小威

Redux 状态树设计探索

  • 506
Loading comments...

More from Ziv 小威