Is it ok to create generic redux update action

↘锁芯ラ 提交于 2019-12-12 04:45:07

问题


Which approach is better and why? There could be more fields than just title and priority.

Having separate action for all changes:

const todoReducer = (state, action) {
  switch (action.type) {
    case 'CHANGE_TITLE' {
      return { ...state, title: action.title }
    }
    case 'CHANGE_PRIORITY' {
      return {...state, priority: action.priority}
    }
  }
}

Having one generic update function:

const todoReducer = (state, action) {
  switch (action.type) {
    case 'UPDATE_PROPERTY' {
      return { ...state, [action.prop]: action.value }
    }
  }
}

回答1:


Benefit of having separate action is that your code would be much more readable and anyone can understand what's happening by just reading it.

switch (action.type) {
    case 'CHANGE_TITLE' {
      return { ...state, title: action.title }
    }
    case 'CHANGE_PRIORITY' {
      return {...state, priority: action.priority}
    }
}

Like in the example you provided, Once can easily know what reducer will do by just reading the action.

The only disadvantage of having separate action (which I can think of ) is, if too many actions are there which performs the same kind of changes then the code will become much lengthy and DRYness of the code will not be maintained.

So in that case, you can consider creating the generic action and use it for all the changes. So in future you ever need to make some changes, you will need to change that only action. Here is the nice question related to DRY principle in coding. https://softwareengineering.stackexchange.com/questions/103233/why-is-dry-important

If code readability is not of much concern and you want your code to be as short as possible and also want to maintain DRYness of code then you can create generic action.

In terms of performance, I don't think it will affect the performance.



来源:https://stackoverflow.com/questions/42116228/is-it-ok-to-create-generic-redux-update-action

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!