首页 > 解决方案 > componentDidUpade 更新子数组并合并

问题描述

我的反应组件有问题。我有父母,我有API调用从数据库返回数据,然后我将两个结果数组传递给孩子。

   <Child items1={this.state.items1} items2={this.state.items2} />

在孩子中,我必须通过相同的 ID 合并这两个数组,并且 = 来声明。

  public componentDidUpdate(prevProps) {
   //Have to check if these props are updated here
        const mergeArray = (source, merge, by) => source.map(item => ({
          ...item,
          ...(merge.find(i => i[by] === item[by]) || {}),
        }));
        this.setState({
          itemsMerged: mergeArray(this.props.items1, this.props.items2,'Id')
        });
      }

如果它们更新,我需要检查两个道具:

 public componentDidUpdate(prevProps) {
    if (this.props.items1 !== prevProps.items1) {
        console.log(this.props.items1);
      }

    if(this.props.items2 !== prevProps.items2) {
      console.log(this.props.items2);
    }
  }

如何嵌套这两个条件或以正确的方式计算出来。

标签: reactjs

解决方案


您可以创建一个

合并 = new Map('你的元素 id',{你的元素})

并且在每次 componentDidUpdate 中,您获取两个数组并使用其 id 更新地图中的每个元素,然后您可以使用地图以适当的方式更新状态


推荐阅读