Redux reducer todolist不可变等效

时间:2016-01-16 00:08:47

标签: reactjs redux immutable.js

我正在尝试重写immutable.js中的redux todo示例,到目前为止,我刚刚将initalstate设置为一个不可变列表并更改了添加和取消而不是扩展运算符,它似乎工作正常。形成不可变的文档它似乎说你可以使用所有这些unshift,push等..在列表中,所以我认为这可能没问题。

我见过一些例子,而不是.List(),他们使用.fromJS()来包装正在推送/取消等等的对象.fromJS()

所以,我的问题

是否需要使它变得不可变?

const initialState = Immutable.List([{
  text: 'Use Redux',
  marked: false,
  id: 0
}]);

export default function todos(state = initialState, action) {
  switch (action.type) {

    case ADD_TODO:
    return state.unshift({
      id: state.reduce((maxId, todo) => Math.max(todo.id, maxId), -1) + 1,
      completed: false,
      text: action.text
    });

    case DELETE_TODO:
      return state.filter(todo =>
        todo.id !== action.id
      )

    case EDIT_TODO:
      return state.map(todo =>
        todo.id === action.id ?
          Object.assign({}, todo, { text: action.text }) :
          todo
      )

    case COMPLETE_TODO:
      return state.map(todo =>
        todo.id === action.id ?
          Object.assign({}, todo, { completed: !todo.completed }) :
          todo
      )

    case COMPLETE_ALL:
      const areAllMarked = state.every(todo => todo.completed)
      return state.map(todo => Object.assign({}, todo, {
        completed: !areAllMarked
      }))

    case CLEAR_COMPLETED:
      return state.filter(todo => todo.completed === false)

    default:
      return state
  }
}

0 个答案:

没有答案