【问题标题】:Immutable push/add (redux/immutable.js)不可变推送/添加 (redux/immutable.js)
【发布时间】:2015-10-11 22:34:40
【问题描述】:

我在 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'
    }
  }  
})

【问题讨论】:

    标签: javascript reactjs immutability redux


    【解决方案1】:

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

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

    如果您需要更新内容(例如,页脚有名称和值,但是您正在更新它以使其也具有样式属性),您可以使用更像 Object.assign 的 mergeIn:

    const myNewData = {footer: {style: "myStyle"}}
    console.log(state.mergeIn(["page1"], fromJS(myNewData);
    
      --> { page1: { name: 'Footer'
                   , value: "I'm a footer!"
                   , style: 'myStyle'
                   }
          } 
    

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-02-22
      • 2018-10-02
      • 2018-01-21
      • 1970-01-01
      • 2016-10-30
      • 1970-01-01
      • 2016-10-05
      • 2015-02-01
      相关资源
      最近更新 更多