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



我的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"
},
...
}

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

以下是我如何尝试更新reducer中的Status属性,但它似乎不起作用,我的状态保持不变。

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

您可以这样做:

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

此外,我个人认为,最好在这里使用小大小写的财产名称,以避免错误。示例:

transactionId: 1, status: "Pending", type: "Withdrawal", clientName...

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

如果直接在state中获取transactions对象

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

如果没有,则,您需要使用以下内容:

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

事务应该是一个数组(它是实体的集合(。"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)
}

相关内容

  • 没有找到相关文章

最新更新