我有一个嵌套节点树的应用程序。所有节点都是同一类型。
{
id: 1,
title: "node_1",
children: [
{
id: 2,
title: "node_2",
children: []
},
{
id: 3,
title: "node_3",
children: []
}
]
}
当用户扩展某个节点(例如id === 3的节点)时,我必须对数据库执行请求并在id === 3的节点的“children”属性中插入响应(数组子节点)。所以结果app状态应该是这样的:
{
id: 1,
title: "node_1",
children: [
{
id: 2,
title: "node_2",
children: []
},
{
id: 3,
title: "node_3",
children: [
{
id: 4,
title: "node_4",
children: []
},
{
id: 5,
title: "node_5",
children: []
}
]
}
]
}
如何在node_3 children属性中粘贴子数组?
答案 0 :(得分:1)
Redux商店中关系数据或规范化数据的建议方法是将其组织为"标准化"时尚,类似于数据库表。这样可以更轻松地管理更新。请参阅http://redux.js.org/docs/FAQ.html#organizing-state-nested-data,How to handle tree-shaped entities in Redux reducers?和https://github.com/reactjs/redux/pull/1269。
答案 1 :(得分:1)
假设:
players = {} # One definition used by all methods
def addPlayer(players): # players as an argument
newName = input("Add a player's Name: ")
newPhone = input("Telephone number: ")
newNumber = input("Jersey number: ")
# Don't redefine it!
players[newName] = newName, newPhone, newNumber
def removePlayer(players): # players as an argument
removeName = input("What name would you like to remove? ")
# Don't redefine it!
if removeName in players:
del players[removeName]
else:
print("Sorry", removeName, "was not found!")
# rest of code adjusted
然后,在减速器中你会做:
const layer1Id = 1;
const layer2Id = 3;
const newArray = [
{
id: 4,
title: "node_4",
children: [],
},
{
id: 5,
title: "node_5",
children: [],
}
];
确保不改变以前的状态。 如果动态或深度嵌套,我建议你写一些递归函数并使用它。
编辑:这是示例递归解决方案(未经测试)。 return Object.assign({}, state, { children: state.children.map(child => {
if (child.id !== layer1Id) return child;
return Object.assign({}, child, { children: child.children.map(node => {
if (node.id !== layer2Id) return node;
return Object.assign({}, node, { children: node.children.concat(newArray) });
})});
})});
按级别排序(即:indices
表示第一级的ID,indices[0]
表示第二级的ID:
indices[1]
答案 2 :(得分:-1)
只需遍历children
数组并推送以纠正其中一个。
var id = expandedItemId;
for(var i = 0; i < obj.children.length; i++){
if(obj.id == expandedItemId){
obj.children.push(`data got from server`);
}
}