2 回答
TA贡献1825条经验 获得超6个赞
你可以试试这个:
updateRoleTypes = () => {
this.setState(prevState => {
const names = prevState.roles.map(role => role.role_type.display.toLowerCase())
const updated = APIresponse.filter(r => names.includes(r.display.toLowerCase()))
return {
roles: [
...prevState.roles.filter(row => !APIresponse.find(responseRow => responseRow.display.toLowerCase() === row.role_type.display.toLowerCase())),
...updated,
],
}
})
}
TA贡献1805条经验 获得超9个赞
您可以修改state? 如果是这种情况,您可以将 的数据类型修改roles为一个object of objects(这可以使用code角色的作为对象的键),而不是一个array of objects。这将帮助您访问和检查每个角色的特定key。
这样,您应该能够只运行一个循环来检查您是否role存在新的循环,state如果是则更新它。
代码
const state = {
roles: {
"MANG": { role_type: { display: "Manager" } },
"ACCT": { role_type: { display: "Accounting" } },
"DEV": { role_type: { display: "Developer" } }
}
};
const response = [
{
uuid: "a49-a2a5-fcce",
link: "organizations/roletypes/a49-a2a5-fcce/",
code: "MANG",
display: "MANAGER",
description: "MANAGER"
},
{
uuid: "681fbe",
link: "organizations/roletypes/681fbe/",
code: "SUPSPEC",
display: "Support Specialist",
description: "Support Specialist"
},
{
uuid: "0331ddccf",
link: "organizations/roletypes/0331ddccf/",
code: "PROJMANG",
display: "Project Manager",
description: "Project Manager"
}
];
const updateRoleTypes = newRoles => {
let _roles = state.roles;
newRoles.forEach(nR => {
if (_roles[nR.code]) {
_roles[nR.code].role_type = nR;
}
});
return _roles;
};
这将返回您的突变,state您只需要setState使用新值即可。
添加回答
举报