繁体   English   中英

不可变的推送/添加(redux / immutable.js)

[英]Immutable push/add (redux/immutable.js)

我在redux reducer中有一个不可变的对象作为状态,并且正在尝试将对象添加/更新到列表中。

这是我的减速器:

import { fromJS } from 'immutable'

const initialState = fromJS({
  editable: true
})

export default (state = initialState, action) => {
  switch(action.type) {

    case 'CONTENT_MODE': {
      return state.set('editable', action.editable ? false : true) 
    }

    case 'UPDATE_CONTENT': {
      return state.set(action.page, action.content)
      // action.page = String
      // action.content = {}
    }

    default: {
      return state
    }

  }
}

我想向页面键添加对象,但是如果当前存在,则更新值。 我已经尝试过updateIn和add()回调,但是我对immutable.js还是相当陌生,并且不确定如何正确处理它。

set()方法完全重写了'page'值,而我需要推送该值并仅在该值存在时进行设置,最后是:

const initialState = fromJS({
  editable: true,
  home: {
    title: {
      name: 'this is the name',
      value: 'this is the value'
    },
    body: {
      name: 'this is the name',
      value: 'this is the value'
    }
  },
  page1: {
    title: {
      name: 'this is the name',
      value: 'this is the value'
    },
    body: {
      name: 'this is the name',
      value: 'this is the value'
    }
  }  
})

如果您知道要从操作中添加内容的完整路径,则可以将SetIn与键路径一起使用。 例如,假设您要向第1页添加页脚:

const footer = {name: 'Footer', value: "I'm a footer!" }
return state.setIn(["page1", "footer"], fromJS(footer)

如果您需要更新内容(即说页脚具有名称和值,但随后将其更新为还具有样式属性),则可以使用mergeIn,它更像Object.assign:

const myNewData = {footer: {style: "myStyle"}}
console.log(state.mergeIn(["page1"], fromJS(myNewData);

  --> { page1: { name: 'Footer'
               , value: "I'm a footer!"
               , style: 'myStyle'
               }
      } 

如果您合并到另一个对象中,它将添加到page1的属性中。 如果该对象具有相同名称的属性,则该值将被覆盖。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM