在Redux中更新嵌套对象的属性

时间:2020-05-10 13:18:58

标签: reactjs redux react-redux immutability

我的Redux状态具有以下结构:

const state = {
 transactions: {
    1: {
       TransactionId: 1, Status: "Pending", Type: "Withdrawal", ClientName: "Paul Carter", Amount: "$28.43"
    },

    2: {
      TransactionId: 2, Status: "Completed", Type: "Refill", ClientName: "Caldwell Reid", Amount: "$45.16"
  },
...
}

假设我有transactions,从id更新/删除对象的正确方法是什么?

这是我尝试更新Status中的reducer属性的方法,但是它似乎不起作用,我的状态保持不变。

const transactionsReducer = (state, action) => {
    case CHANGE_TRANSACTION_STATUS:
      return {
        [state.transactions[action.id].Status]: action.status
       }
}

3 个答案:

答案 0 :(得分:2)

您可以这样做:

parsedCodedParams = {a: "1",b:"2", c: "3"} 
mappingParams={ d:"1",z:"5"} 

此外,我个人认为,最好在此处使用小型框来表示属性名称,以免出错。示例:

parsedCodedParams= {d: "1",b:"2", c: "3"} 

答案 1 :(得分:1)

在这里,它应该看起来像这样:

如果您直接在transactions中获得state对象

return {
    ...state,
    [action.id]: {
        ...state[action.id] ,
        Status : action.status
    }
}

如果不是这样的话,则需要使用:

return {
    ...state,
    transactions : {
        ...state.transactions ,
        [action.id]: {
            ...state.transactions[action.id] ,
            Status : action.status
        }
    }
}

答案 2 :(得分:0)

事务应该是一个数组(它是实体的集合)。 “ id”键是多余的,它已经由“ TransactionId”(单一事实来源)表示。 像这样:

const state = {
 transactions: [
     {
       TransactionId: 1, Status: "Pending", Type: "Withdrawal", ClientName: "Paul Carter", Amount: "$28.43"
    },

     {
      TransactionId: 2, Status: "Completed", Type: "Refill", ClientName: "Caldwell Reid", Amount: "$45.16"
  },
...
]

然后,您可以简单地使用过滤器进行删除,并使用映射进行更新:

return {
    ...state,
    transactions: state.transactions.filter(txn => txn.TransactionId !== action.deletedId)
}