我的州看起来像这样:
{
"account":{
"id":7,
"categories":[
{
"id":7,
"products":[
{
"productId":54
}
]
},
{
"id":9,
"products":[
{
"productId":89
}
]
}
]
}
}
现在在我的Reducer中我可以返回当前状态,如:
return {...state}
我可以为帐户设置一个新值,如:
return { ...state, account: action.account }
但是如何从集合中过滤嵌套项?
如果我这样做,我的过滤器会返回错误的类别,因为我想返回一个帐户:
return {...state, account: state.account.categories.filter((c) => c.id === 4)}
如果我执行上述操作,而不是拥有帐户值,我现在将帐户设置为类别集合。
有人可以向我解释如何更深入地获得一个级别,即通过过滤嵌套的类别集合将帐户值设置为新值。
我认为您遇到的挑战是您正在静音原始数据源,因此无法应用其他过滤器,因为原始数据已丢失。要解决此问题,我建议您创建一个新字段来存储所选类别。
return {
...state,
account: {
...state.account,
selectedCategory: state.account.categories.find((c) => c.id === action.categoryId)
}
}