【问题标题】:How to add an object property to another property in the state?如何将对象属性添加到状态中的另一个属性?
【发布时间】:2017-07-28 07:20:04
【问题描述】:

我正在我的 react-redux 应用程序中设置操作和减速器。我需要一个函数来更新状态中的属性并将对象添加到其列表中,如果可能的话,使用扩展语法。到目前为止,这是我所拥有的:

const defaultState = {
  genres: {}
}

export default function(state = defaultState, action) {
  switch(action.type) {
    case 'ADD_GENRE':
      return {
        ...state,
        genres[action.name]: action.list //new code here
      }
    default:
      return state;
  }
}

我需要像数组一样使用它的属性名称动态访问流派属性,如下所示:

const getMusicFromGenre = (genre) => {
  return state.genres[genre];
}

reducer 应该接受以下动作,然后相应地修改状态:

// action
{
  type: 'ADD_GENRE,
  name: 'Rock',
  list: ['Bohemian Rhapsody', 'Stairway to Heaven', 'Hotel California']
}

// old state
{
  genres: {
    "Pop": ['Billie Jean', 'Uptown Funk, 'Hey Jude']
  }
}

// new state
{
  genres: {
    "Pop": ['Billie Jean', 'Uptown Funk, 'Hey Jude'],
    "Rock": ['Bohemian Rhapsody', 'Stairway to Heaven', 'Hotel California']
  }
}

如有必要,我愿意使用不同的方法。

【问题讨论】:

    标签: javascript reactjs ecmascript-6 redux


    【解决方案1】:

    您在正确的轨道上,但需要分别处理每个级别的嵌套。这是我为http://redux.js.org/docs/recipes/reducers/ImmutableUpdatePatterns.html 写的一个例子:

    function updateVeryNestedField(state, action) {
        return {
            ....state,
            first : {
                ...state.first,
                second : {
                    ...state.first.second,
                    [action.someId] : {
                        ...state.first.second[action.someId],
                        fourth : action.someValue
                    }
                }
            }
        }
    }
    

    您可能还想阅读我在http://redux.js.org/docs/recipes/reducers/PrerequisiteConcepts.html#immutable-data-managementhttps://github.com/markerikson/react-redux-links/blob/master/immutable-data.md 链接的一些关于不可变数据处理的文章。

    【讨论】:

    • 我试图自己找到解决方案,但问题太难谷歌了。感谢您的链接,明天肯定会在喝一大杯咖啡时阅读它
    【解决方案2】:

    immutability-helper 是一个非常有用的状态更新库。在您的情况下,它将像这样使用,如果没有现有项目,它将创建一个新数组,或者如果有预先存在的项目,则将现有项目与操作列表连接:

    import update from 'immutability-helper';
    
    const defaultState = {
      genres: {}
    }
    
    const createOrUpdateList = (prev, list) => {
       if (!Array.isArray(prev)) {
           return list;
       }
       return prev.concat(list);
       // or return [...prev, ...list] if you prefer
    }
    
    export default function(state = defaultState, action) {
      switch(action.type) {
        case 'ADD_GENRE':
          return update(state, {
              genres: {
                  [action.name]: {
                      $apply: prev => createOrUpdate(prev, action.list)
                  }
              }
          });
        default:
          return state;
      }
    }
    

    【讨论】:

    • 这是一个有用的插件,使代码更易于查看。谢谢
    猜你喜欢
    • 2015-11-15
    • 2022-06-29
    • 2020-11-05
    • 2020-06-22
    • 1970-01-01
    • 2016-09-14
    • 2022-07-21
    • 2016-07-18
    • 2021-12-09
    相关资源
    最近更新 更多