使用Reducer Redux中的新内容更新数组



我仍在研究函数式编程以及如何从化简器返回非突变对象。

我正在尝试替换化简器中旧对象的内容,而不会改变旧状态。

所以如果旧状态是

 {
        Actors:"Michael Keaton, Jack Nicholson, Kim Basinger, Robert Wuhl"
        Awards:"Won 1 Oscar. Another 9 wins & 22 nominations."
        Country:"USA, UK"
        Director:"Tim Burton"
 }

新状态是

{
        Actors:"George Clooney"
        Awards:"Won 9 Oscars."
        Country:"USA"
        Director:"Quentin Tarantino"
 }

我的减速器看起来像这样

function reducer(state = {}, action){
  switch(action.type) {
    case 'GET_MOVIE':
      return //new Array here that has not been mutatated
    default:
        return state;
  }
}

我的有效载荷看起来像这样

{
    Actors:"Michael Keaton, Jack Nicholson, Kim Basinger, Robert Wuhl"
    Awards:"Won 1 Oscar. Another 9 wins & 22 nominations."
    Country:"USA, UK"
    Director:"Tim Burton"
}

如果对象的所有值每次都在更改,则可以简单地将新有效负载作为新状态返回。但是,如果只有某些值在更改,则可以使用 ES6 Object.assign 或 object-assign 作为 npm 模块。

如果所有值每次都在变化,那么,

function reducer(state = {}, action){
   switch(action.type) {
    case 'GET_MOVIE':
      return action.payload;
    default:
        return state;
  }
}

如果某些值正在更改,则,

function reducer(state = {}, action){
   switch(action.type) {
    case 'GET_MOVIE':
      // let say Actors field changed, then 
      return Object.assign({}, state, {Actors: "Michael Keaton, Jack Nicholson, Kim Basinger, Robert Wuhl" });
    default:
        return state;
  }
}

我对为什么在处理对象时需要数组运算符有点困惑。使用此当前状态,可以通过以下两种方式之一执行此操作,具体取决于生成工具、polyfill 和/或目标浏览器。

使用Object.assign()

function reducer(state = {}, action){
  switch(action.type) {
    case 'GET_MOVIE':
      return Object.assign({}, state, {
        Actors: action.Actors,
        Awards: action.Awards,
        Country: action.Country,
        Director: action.Director
      });
    default:
        return state;
  }
}

或者使用点差运算符...

function reducer(state = {}, action){
  switch(action.type) {
    case 'GET_MOVIE':
      return {
        ...state,
        Actors: action.Actors,
        Awards: action.Awards,
        Country: action.Country,
        Director: action.Director
      }
    default:
        return state;
  }
}

只需使用非可变函数并返回新的数据结构。

如果你的状态只是 {a: 1, b: 2, c: 3},并且您希望它变成 {a: 4, b: 5, c: 6},

只需返回 {a: 4, b: 5, c: 6}。

function reducer(state = {a: 1, b: 2, c: 3}, action){
  switch(action.type) {
    case 'GET_MOVIE':
      return action.payload // assuming action.payload = {a: 4, b: 5, c: 6}
    default:
        return state;
  }
}

当你想要新的状态 = [{a:1,b:2,c:3},{a:4, b:5, c: 6}] 时,它会变得更有趣。

对于可变函数

与非可变函数的良好列表,这很有帮助:https://jeff.is/blog/mutative-vs-non-mutative-array-methods-in-js.html

我还发现 React 的不可变性助手非常适合深度嵌套结构。 他们使用 Mongo 风格的语法。

最新更新