gpt4 book ai didi

javascript - 从父状态重新排序子组件时出现问题

转载 作者:行者123 更新时间:2023-11-30 20:31:41 26 4
gpt4 key购买 nike

我正在从 Parents 状态的数组构建子元素列表。我可以将信息从 child 传递回 parent ,并更新 parent 的状态。

但是,当我尝试对数组中的对象重新排序(以更改 DOM 中子项的顺序)时,它会更改父级状态中数组的顺序,但不会更新它们在 dom 中的位置重新渲染。

回顾一下:

  • 它会重新渲染父级和子级
  • 它确实改变了 this.state.array 中 objs 的顺序
  • 它不会重新排列 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>
);
}
}

最佳答案

你不应该在 React 中使用数组索引作为列表键。请改用业务 key 。例如,当您的项目对象看起来像:

const array = [{ id: 1, value: 'a' }, { id: 2, value: 'b' }, ...]

你可以使用id作为key:

<Child key={item.id}
updateChild={this.updatechild}
moveChild={this.moveChild}
item={item.value}
/>

您可以在 official documentation 中找到有关列表和键的更多信息

关于javascript - 从父状态重新排序子组件时出现问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50277391/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com