【发布时间】:2021-02-23 10:58:28
【问题描述】:
我正在研究一个解决方案,其中我有一个包含子元素的深层父数组
这是数组的样子
[
{
"id": "1",
"Name": "John Doe",
"children":
[
{
"id": "1.1",
"name": "John doe 1.1"
},
{
"id:": "1.2",
"name:": "John doe 1.2"
},
{
"id": "1.3",
"name": "John doe 1.3",
"children":
[
{
"id": "1.3.1",
"name": "John doe 1.3.1"
}
]
}
]
},
{
"id": "2",
"Name": "Apple",
"children":
[
{
"id": "2.1",
"name": "Apple 2.1"
},
{
"id:": "1.2",
"name:": "Apple 1.2"
}
]
}
]
基本上,我有一个功能,只要用户点击我想添加与该行相关的子级的行,我就有一个表格,
例如,每当我单击 id 为 1 的行时,我通过将行作为参数传递来调用 click 函数,找到行的索引并在其下附加子项以及维护状态,我的解决方案仅适用于嵌套的一层孩子,假设如果我想在 children 下添加 children 属性,它不起作用
这是我写的函数
const expandRow = (row) => {
const index = _(this.state.data)
.thru(function(coll) {
return _.union(coll, _.map(coll, 'children') || []);
})
.flattenDeep()
.findIndex({ id: row.id });
console.log(index)
if (index !== -1) {
let prevState = [...this.state.data];
let el = _(prevState)
.thru(function(coll) {
return _.union(coll, _.map(coll, 'children') || []);
})
.flattenDeep()
.find({ id: row.id });
console.log(el)
el.children = [
{ id: '_' + Math.random().toString(36).substr(2, 5), name: "sfsdfds1", isExpanded:false,parentId:row.id },
{ id: '_' + Math.random().toString(36).substr(2, 5), name: "sfsdfds2",isExpanded:false,parentId:row.id },
];
this.setState({data:[...this.state.data],prevState},()=>{console.log(this.state.data)})
}
updateState(row.id, { isExpanded: true });
};
我还想与它一起维护状态,因此每当用户添加新行时,我的组件都会重新渲染。
【问题讨论】:
标签: javascript reactjs lodash