reactjs - 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);
}
}
如何嵌套这两个条件或以正确的方式计算出来。
解决方案
您可以创建一个
合并 = new Map('你的元素 id',{你的元素})
并且在每次 componentDidUpdate 中,您获取两个数组并使用其 id 更新地图中的每个元素,然后您可以使用地图以适当的方式更新状态
推荐阅读
- shell - 如何以安全的方式在 Jenkins shell 脚本中传递密码?
- php - 获取所有行在列中有值
- amazon-web-services - 如何保持多个实例之间的文件同步?这样只有一个实例会拾取文件并处理它
- javascript - 为什么我的 JS 对象作为未定义值添加到数组中?
- shell - 如何在 groovy 脚本的 shell 块中声明一个新变量?
- html - 使用内联 CSS 为标签内的标签设置样式
- c - 插入排序的过程
- .net - xml 转换定位器匹配未按预期工作
- spring - Spring mvc 将相同的 url 重定向到不同的主机
- java - getter 在设置后无法访问它的值