群体 vs 个体

我们会注意到在我们实现的todos里,其实是在对所有的todo进行遍历寻找然后进行操作,那么这里实际上做了两件事,为了使代码的逻辑更加清晰,reducer的功能更单一,我们将针对todoItem的reducer->todo抽离出来。

// Reducer composition => separate the reducer as possible
// It will make your reducer logic clear and enhance the reuseability
// Micro reducer: only deal with state of single todo item,
// that's why we extract this logic from the previous reducer with obscure logic

const todo = ({state, action}) => {
  switch (action.type) {
    case: 'ADD_TODO':
      return {
        id: action.id,
        text: action.text,
        completed: false
      }
    case 'TOGGLE_TODO' :
      return action.id === state.id ? 
        { ...state, completed: !state.completed } : state
    default: 
      return state
  }
}

const todos = ({state = [], action}) => {
  switch (action.type) {
    case 'ADD_TODO' :
      return [
        ...state,
        todo(undefined, action)
      ]
    case 'TOGGLE_TODO' :
      return state.map(t => todo(t, action))
  }
}

现在看起来是不是代码语义化更好了? 逻辑也更清晰,在以后的组件抽象中,我们要注意区分群体和个体的概念,尽可能的将抽象出最小个体组件,用来组成更大的组件。

results matching ""

    No results matching ""