Is it ok to create generic redux update action

2019-09-14 20:04发布

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 }
    }
  }
}

标签: reactjs redux
1条回答
你好瞎i
2楼-- · 2019-09-14 20:38

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.

查看更多
登录 后发表回答