2

我在 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() 方法完全重写了“页面”值,而我需要推送该值并且仅在它存在时才设置,最终得到:

例子

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'
    }
  }  
})
4

1 回答 1

0

如果您知道要从操作中添加内容的完整路径,则可以将 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 中。如果该对象具有同名的属性,则该值将被覆盖。

于 2016-03-18T01:20:09.723 回答