【发布时间】:2018-10-20 23:45:02
【问题描述】:
我正在从父母状态的数组中构建子元素列表。我可以将来自孩子的信息传回给父母,并更新父母的状态。
但是,当我尝试对数组中的对象重新排序(以更改 DOM 中子项的顺序)时,它会更改数组在 Parent 状态下的顺序,但不会更新它们在 dom 中的位置重新渲染。
回顾一下:
- 它确实会重新渲染父级和子级
- 它确实改变了 this.state.array 中 obj 的顺序
- 它不会对 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>
);
}
}
【问题讨论】:
标签: javascript reactjs