[英]How to update certain key values in an object nested in the redux state
I have the following data:我有以下数据:
Project : {id:10,
requirements: [{id:1,
title:test},
{id:2,
title:test2}]
}
and和
action.payload : {id:1,
title:changed_title}
What i wish to update the requirement object of id:1
within my redux reducer.我希望在我的 redux 减速器中更新
id:1
的 object 要求。
Heres what i have so far but it doesn't seem to be working and its super messy:这是我到目前为止所拥有的,但它似乎没有工作并且它超级混乱:
case 'requirements_update': return (updateObject(state, project: {...state.project , requirements: state.project.requirements.filter(requirement =>
{if(requirement.requirement_id === action.payload.requirement_id)
return(action.payload) }
})}))
You can use map and id check to update project您可以使用 map 和 id check 来更新项目
project : state.project.map(project => project.id === payload.id ? payload : project)
The double spreading at the bottom is to merge current requirement properties with action payload, (action payload properties will have priority since they will override existing ones)底部的双重扩展是将当前需求属性与动作负载合并,(动作负载属性将具有优先级,因为它们将覆盖现有的)
case 'requirements_update':
return {...state, state.project: {...state.project , requirements: state.project.requirements.map(requirement => {
if (requirement.id === action.payload.id) {
return {...requirement, ...action.payload}
} else {
return requirement
}
}}}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.