使用地图

时间:2017-11-14 09:34:25

标签: javascript reactjs ecmascript-6 redux

函数式编程引入了不可变的,因此es6的映射在处理数据时非常流行,特别是在数组和对象中。

我的redux减速器低于

const todos = (state = [], action) => {
    switch(action.type) {
        case 'TOGGLE_TODO': {
            return state.map(todo => 
                todo.id !== action.id ? todo 
                : {
                ...todo, checked: !todo.checked
                }
            )
        }
        default:
           return state
    }

}

除了上述方法之外,更改已检查属性的替代方法是什么?代码甚至可读吗?

有人喜欢这个

switch (action.type) {
        case "TOGGLE_TODO":
            return [
                ...state.slice(0, action.id),
                {...state[action.id], isCompleted: !state[action.id].isCompleted},
                ...state.slice(action.id + 1)
            ]
        default:
            return state;
    }

1 个答案:

答案 0 :(得分:0)

这就是我要做的事;

const todos = (state = [], action) => {
  switch(action.type) {
    case 'TOGGLE_TODO': {
      let newState = state.concat([]);
      newState.any((item) =>
        item.id == action.id && 
          (item = { ...item, checked: !item.checked })
      ); 

      return newState;
    }
    default:
       return state;
  }
}

如果您可以将待办事项列表的数据结构更改为地图,那么我认为以下内容看起来更具可读性。

const todos = (state = {}, action) => {
  switch(action.type) {
    case 'TOGGLE_TODO': {
      let itemToChange = state[action.id];
      return { 
        ...state, 
        [action.id]: { 
          ...itemToChange, 
          checked: !itemToChange.checked 
        }
      };
    }
    default:
       return state
  }
}