如何销毁减速器中的对象(REACT)
How to destruct object in reducer (REACT)
我在状态中有以下用户数据
userData : {
isValidCheckup: true,
accounts: {
userAccount: [
{
accountType: 'checkings',
includeInCheckup: false
},
{
accountType: 'checkings',
includeInCheckup: false
}
]
}
现在,我有一个 reducer 来处理上述数据的操作。注意:我只想更新 includeInCheckup
字段。取决于作为有效负载接收到减速器的 accountType
。
这是我使用的reducer函数
case UPDATE_USER_DATA: {
const { field, value } = action.payload; // field='checkings', value=true
return {
...state,
userData: {
...state.userData
}
}
}
如您所见,我正在从有效载荷到减速器中获取 field='checkings', value=true
。我如何根据字段值将此值具体更新为 includeInCheckup
属性。
有人可以解释一下吗。
When I get field as 'checkings', I update the first element of array
'userAccount' and when I get field as 'savings, I will update the
second element of array.
例如 state,我假设 userAccount[0]
是支票账户类型,userAccount[1]
是储蓄账户类型,数组的长度始终为 2。
userData : {
isValidCheckup: true,
accounts: {
userAccount: [
{
accountType: 'checkings',
includeInCheckup: false
},
{
accountType: 'savings',
includeInCheckup: false
}
]
}
复制正在更新的每个级别的状态,然后通过创建新的 object/array 引用来更新 属性。您可以简单地映射 userAccount
数组并检查帐户类型是否与操作有效负载字段匹配,然后更新 includeInCheckup
属性.
case UPDATE_USER_DATA: {
const { field, value } = action.payload; // field='checkings', value=true
return {
...state,
userData: {
...state.userData,
accounts: {
...state.userData.accounts,
userAccount: state.userData.accounts.map((account) =>
account.accountType === field
? {
...account,
includeInCheckup: value
}
: account
)
}
}
};
}
我在状态中有以下用户数据
userData : {
isValidCheckup: true,
accounts: {
userAccount: [
{
accountType: 'checkings',
includeInCheckup: false
},
{
accountType: 'checkings',
includeInCheckup: false
}
]
}
现在,我有一个 reducer 来处理上述数据的操作。注意:我只想更新 includeInCheckup
字段。取决于作为有效负载接收到减速器的 accountType
。
这是我使用的reducer函数
case UPDATE_USER_DATA: {
const { field, value } = action.payload; // field='checkings', value=true
return {
...state,
userData: {
...state.userData
}
}
}
如您所见,我正在从有效载荷到减速器中获取 field='checkings', value=true
。我如何根据字段值将此值具体更新为 includeInCheckup
属性。
有人可以解释一下吗。
When I get field as 'checkings', I update the first element of array 'userAccount' and when I get field as 'savings, I will update the second element of array.
例如 state,我假设 userAccount[0]
是支票账户类型,userAccount[1]
是储蓄账户类型,数组的长度始终为 2。
userData : {
isValidCheckup: true,
accounts: {
userAccount: [
{
accountType: 'checkings',
includeInCheckup: false
},
{
accountType: 'savings',
includeInCheckup: false
}
]
}
复制正在更新的每个级别的状态,然后通过创建新的 object/array 引用来更新 属性。您可以简单地映射 userAccount
数组并检查帐户类型是否与操作有效负载字段匹配,然后更新 includeInCheckup
属性.
case UPDATE_USER_DATA: {
const { field, value } = action.payload; // field='checkings', value=true
return {
...state,
userData: {
...state.userData,
accounts: {
...state.userData.accounts,
userAccount: state.userData.accounts.map((account) =>
account.accountType === field
? {
...account,
includeInCheckup: value
}
: account
)
}
}
};
}