Redux:将用于非平坦状态的“ reduces”与避免创建大量reducer结合起来

时间:2018-10-31 08:18:52

标签: javascript redux

我学习Redux,并尝试创建和组合 reducers 为学校,班级和学生建立简单模型。我想实现我的 state 的这种结构:

const model = {
  schools:[
    { id: "91cb54b3-1289-4520-abe1-d8826d39fce3",
      name: "School #25", address: "Green str. 12",
      classes: [
        { id: "336ff233-746f-441b-84c7-0e6c275a7e24", name: "1A",
          students: [
            { id: "475dd06e-a52d-4d90-aa07-46eab7c029a7", name: "Ivan Ivanov",
              age: 7, phones: ["+7-123-456-78-90"] }
          ]
        }
      ]
    }
  ]
};

我知道我可以为每个属性创建reducer,但是如果模型很大,这将非常困难。因此,我想减少减速器的数量。我以为解决方案很简单,但是我的减速器组合起来却遇到了问题...

此外,我看到了附加问题...例如,对于当前的实现,如何在第二所学校添加class实例?这意味着我要指出学校的身份证...但是如果我需要添加学生的电话,那么我就需要指出每个父母的身份证以获取必要的学生(即学校,班级和学生的身份证)...可能我目前的执行方式有误...我不确定...

我很困惑。 :((((我知道如何将combineReducers用于简单的平面模型,但我不知道如何在更复杂的情况下使用它。

这是我的“沙箱”,在那里我学习Redux并尝试将combineReducers用作我的“业务模型”:

import {createStore} from "redux";
import {uuidv4} from "uuid/v4"; // yarn add uuid

const createId = uuidv4; // creates new GUID
const deepClone = object => JSON.parse(JSON.stringify(object));

/**
I will use simple model: the shools, classes, and students:

const model = {
  schools:[
    { id: "91cb54b3-1289-4520-abe1-d8826d39fce3",
      name: "School #25", address: "Green str. 12",
      classes: [
        { id: "336ff233-746f-441b-84c7-0e6c275a7e24", name: "1A",
          students: [
            { id: "475dd06e-a52d-4d90-aa07-46eab7c029a7", name: "Ivan Ivanov",
              age: 7, phones: ["+7-123-456-78-90"] }
          ]
        }
      ]
    }
  ]
};
*/

// ================= Business model ====================
function createSchool(name = "", address = "", classes = []){
  return { id: createId(), name, address, classes };
}

function createClass(name = "", students = []){
  return { id: createId(), name, students };
}

function createStudent(name = "", age = 0, phones = []){
  return { id: createId(), name, age, phones };
}

function createPhone(phone = ""){
  return { id: createId(), phone };
}
// ================= end of Business model =============

const ACTION_KEYS = { // It is used by Action model
  CREATE_SCHOOL: "CREATE_SCHOOL",
  UPDATE_SCHOOL: "UPDATE_SCHOOL",
  DELETE_SCHOOL: "DELETE_SCHOOL",

  CREATE_CLASS: "CREATE_CLASS",
  UPDATE_CLASS: "UPDATE_CLASS",
  DELETE_CLASS: "DELETE_CLASS",

  CREATE_STUDENT: "CREATE_STUDENT",
  UPDATE_STUDENT: "UPDATE_STUDENT",
  DELETE_STUDENT: "DELETE_STUDENT",

  CREATE_PHONE: "CREATE_PHONE",
  UPDATE_PHONE: "UPDATE_PHONE",
  DELETE_PHONE: "DELETE_PHONE",
}

// ==================== Action model ======================

// School actions:

function create_createShoolAction(value = createSchool()){
  // use createSchool() function for 'value' initializing
  return {type: ACTION_KEYS.CREATE_SCHOOL, value };
}

function create_updateShoolAction(value){
  // use createSchool() function for 'value' initializing
  return {type: ACTION_KEYS.UPDATE_SCHOOL, value };
}

function create_deleteShoolAction(id){
  return {type: ACTION_KEYS.DELETE_SCHOOL, id };
}

// Class actions:

function create_createClassAction(value = createClass()){
  // use createClass() function for 'value' initializing
  return {type: ACTION_KEYS.CREATE_CLASS, value };
}

function create_updateClassAction(value){
  // use createClass() function for 'value' initializing
  return {type: ACTION_KEYS.UPDATE_CLASS, value };
}

function create_deleteClassAction(id){
  return {type: ACTION_KEYS.DELETE_CLASS, id };
}

// Student actions:

function create_createStudentAction(value = createStudent()){
  // use createStudent() function for 'value' initializing
  return {type: ACTION_KEYS.CREATE_STUDENT, value };
}

function create_updateStudentAction(value){
  // use createStudent() function for 'value' initializing
  return {type: ACTION_KEYS.UPDATE_STUDENT, value };
}

function create_deleteStudentAction(id){
  return {type: ACTION_KEYS.DELETE_STUDENT, id };
}

// Phone actions:

function create_createPhoneAction(value = createPhone()){
  // use createPhone() function for 'value' initializing
  return {type: ACTION_KEYS.CREATE_PHONE, value };
}

function create_updatePhoneAction(value){
  // use createPhone() function for 'value' initializing
  return {type: ACTION_KEYS.UPDATE_PHONE, value };
}

function create_deletePhoneAction(id){
  return {type: ACTION_KEYS.DELETE_PHONE, id };
}
// ==================== end of Action model ===============

// ========================= Reducers =====================

// This function contains common implementation for all my reducers (I'm lazy).
function reducer(state = [], action, action_keys){
  switch(action.type){
    switch action_keys[0]: { // create new item
      return [...deepClone(state), ...deepClone(action.value)];
      break;
    }
    switch action_keys[1]: { // update existing item
      const index = state.findIndex(n => n.id === action.value.id);
      if(index < 0) return state;
      const clonedState = [...deepClone(state)];
      return [...clonedState.slice(0, index), ...deepClone(action.value),
        ...clonedState.slice(index + 1)];
      break;
    }
    switch action_keys[2]: { // delete existing item
      const index = state.findIndex(n => n.id === action.id);
      if(index < 0) return state;
      const clonedState = [...deepClone(state)];
      return [...clonedState.slice(0, index), ...clonedState.slice(index + 1)];
      break;
    }
    default: { // otherwise return original
      return state;
      break;
    }
  }
}

function schoolReducer(state = [], action){
  return reducer(state, action, [
    ACTION_KEYS.CREATE_SCHOOL,
    ACTION_KEYS.UPDATE_SCHOOL,
    ACTION_KEYS.DELETE_SCHOOL
  ]);
}

function classReducer(state = [], action){
  return reducer(state, action, [
    ACTION_KEYS.CREATE_CLASS,
    ACTION_KEYS.UPDATE_CLASS,
    ACTION_KEYS.DELETE_CLASS
  ]);
}

function studentReducer(state = [], action){
  return reducer(state, action, [
    ACTION_KEYS.CREATE_STUDENT,
    ACTION_KEYS.UPDATE_STUDENT,
    ACTION_KEYS.DELETE_STUDENT
  ]);
}

function phoneReducer(state = [], action){
  return reducer(state, action, [
    ACTION_KEYS.CREATE_PHONE,
    ACTION_KEYS.UPDATE_PHONE,
    ACTION_KEYS.DELETE_PHONE
  ]);
}

// The "top-level" combined reducer
const combinedReducer = combineReducers({
  schools: schoolReducer
  // Oops... How to build the hierarchy of the remaining reducers (classReducer,
  // studentReducer, and phoneReducer)?
});
// =============== end of Reducers =====================

const store = createStore(combinedReducer);

const unsubscribe = store.subscribe(() => console.log("subscribe:",
  store.getState()));

// Now to work with the store...

store.dispatch(create_createShoolAction(createShool("Shool #5", "Green str. 7")));
store.dispatch(create_createShoolAction(createShool("Shool #12", "Read str. 15")));
store.dispatch(create_createShoolAction(createShool("Shool #501", "Wall str. 123")));

// Now, how can I add a new class into the "Shool #12" school?
// store.dispatch(???);

对于这种不平坦的状态,如何正确地创建和组合减速器?

1 个答案:

答案 0 :(得分:1)

  

我知道我可以为每个属性创建减速器,但是它将   如果模型很大,很难。

我不了解您的意思,因为您已经体验到更新嵌套结构有多糟糕:您需要深入研究,搜索字段并谨慎处理更新,以免破坏现有数据。更糟糕的是,使用嵌套结构,渲染React组件的成本会很高,因为更新电话号码将需要您对几乎所有内容进行深度克隆。

通常,我的redux状态图像是一个客户端sql数据库,每个模型(例如,学校,班级,学生)应存储在单独的表中; child应该包含父级id,parent可以包含子级id作为双向搜索的数组。

一种好方法是将每个模型的化简器分解为单独的化简器,并在添加时使用某些中间件(例如redux-thunk或redux-saga)来处理相关模型中的更新-删除任何内容。

如果您懒得分解,那么1个减速器还是可以的。但是您需要规范化数据以更好地进行数据处理:

const initialState = {
  schools: {},
  classes: {},
  students: {}
}

function reducer(state = initialState, actions, action_keys) {
  ...
}

因此您的数据样本可能如下所示:

{
  schools: {
    "91cb54b3-1289-4520-abe1-d8826d39fce3": {
      id: "91cb54b3-1289-4520-abe1-d8826d39fce3",
      name: "School #25",
      address: "Green str. 12",
      classes: [
        "336ff233-746f-441b-84c7-0e6c275a7e24"
      ]
    }
  },
  classes: {
    "336ff233-746f-441b-84c7-0e6c275a7e24": {
      id: "336ff233-746f-441b-84c7-0e6c275a7e24",
      schoolId: "91cb54b3-1289-4520-abe1-d8826d39fce3",
      name: "1A",
      students: [
        "475dd06e-a52d-4d90-aa07-46eab7c029a7"
      ]
    }
  },
  students: {
    "475dd06e-a52d-4d90-aa07-46eab7c029a7": {
      id: "475dd06e-a52d-4d90-aa07-46eab7c029a7",
      classId: "336ff233-746f-441b-84c7-0e6c275a7e24"
      name: "Ivan Ivanov",
      age: 7,
      phones: ["+7-123-456-78-90"]
    }
  }
}

如何实施操作以处理数据更新是您自己的问题,但是通过上述结构,应该可以更轻松地解决问题。