我正在构建父状态数组中的子元素列表。我可以将孩子的信息传递回父母,并更新父母的状态。
但是,当我尝试对数组中的对象进行重新排序(以更改DOM中子节点的顺序)时,它会改变父节点状态中数组的顺序,但是当它没有更新它们在dom中的位置时重新呈现。
回顾一下:
我的理解是它重新渲染,并重新遍历我的列表。如果我将新项目推送到数组的末尾,它将在重新渲染时呈现新项目,但不会使用拼接移动我在数组中移动的项目。
这是一个快速的狙击手,试图展示我的结构:
class Parent extends Component {
constructor(props) {
super();
this.state = {
array: [{obj1}, {obj2}, {obj3}]
}
this.moveChild = this.moveChild.bind(this);
this.updateChild = this.updateChild.bind(this);
}
moveChild(obj) {
//this moves the item left in the array
//obj is state of child passed from child
let index = obj.index;
if (index-- < 0) {
index = 0;
}
this.setState((prevState, props) => {
return this.state.array.splice(index, 0, this.state.array.splice(obj.index, 1)[0]);
});
}
updateChild(obj) {
//updates the state of parent with changes of child.
}
render() {
return ({
this.state.array.map((item, i) =>
<
Child key = {i}
updateChild = {this.updatechild}
moveChild = {this.moveChild}
item = {item}
/> );}
}
}
class Child extends Component {
//has its own state which tracks several parameters.
//has function to pass its state to parent using updateChild
//has function to pass a move operation back to parent
render() {
return (
<button onClick = {this.moveChildFun} > Move < /button>
<button onClick = {this.updateChildFun} > Updates < /button>
);
}
}