是否可以创建通用的 redux 更新操作 [英] Is it ok to create generic redux update action

查看:33
本文介绍了是否可以创建通用的 redux 更新操作的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

哪种方法更好,为什么?可能有更多的字段,而不仅仅是标题和优先级.

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

推荐答案

具有单独操作的好处是您的代码将更具可读性,任何人都可以通过阅读了解正在发生的事情.

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

就像您提供的示例一样,Once 只需阅读操作即可轻松了解 reducer 将执行的操作.

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

单独操作(我能想到的)的唯一缺点是,如果有太多操作执行相同类型的更改,那么代码将变得冗长并且不会保持代码的 DRYness.

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.

因此,在这种情况下,您可以考虑创建通用操作并将其用于所有更改.所以将来你需要做一些改变,你只需要改变那个动作.这是与编码中的 DRY 原则相关的好问题.https://softwareengineering.stackexchange.com/questions/103233/why-is-dry-important

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

如果代码可读性不是什么大问题,并且您希望代码尽可能短并且希望保持代码的 DRYness,那么您可以创建通用操作.

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.

这篇关于是否可以创建通用的 redux 更新操作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆