【问题标题】:Problems reordering child components from parent's state从父状态重新排序子组件的问题
【发布时间】: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


    【解决方案1】:

    您不应该在 react 中使用数组索引作为列表键。请改用业务密钥。例如,当您的 items 对象看起来像这样时:

    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中找到有关列表和键的更多信息

    【讨论】:

    • 哦,伙计,非常感谢 - 我什至没有想过在重新排序时这会如何影响数组。现在可以工作了——但是如果我从没有 ID 的外部来源中提取物品,您对如何为我的物品生成 ID 有什么建议吗?我想如果键无关紧要,只需要唯一我可以为每个导入的键分配一个增量...
    • @BrendanHamman 确切地说,它们必须是独一无二的。如果项目的文本是唯一的,您可以将其用作键。
    猜你喜欢
    • 1970-01-01
    • 2021-04-06
    • 1970-01-01
    • 1970-01-01
    • 2017-09-28
    • 2023-02-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多