【问题标题】:When pushing objects to array, how to not push same object?将对象推送到数组时,如何不推送相同的对象?
【发布时间】:2019-09-06 09:49:56
【问题描述】:

我正在使用复选框中选中的对象创建新数组。但是当我再次提交时,出现错误“flattenChildren(...):遇到两个具有相同密钥的孩子,.$3。子密钥必须是唯一的;当两个孩子共享一个密钥时,只会使用第一个孩子。 "我只想推送独特的对象。

我正在使用反应

handleSubmit(){

    let students = []
    for(let idx in this.state.checked){
        if(this.state.checked[idx] ){
            students.push(this.state.allStudent[idx])
        }
    }
    console.log('students', students)
    this.setState({
        studentList: update(this.state.studentList, {$push: students})
    })

}

【问题讨论】:

  • 对不起,我是新手。感谢您的帮助!
  • 你不必为不知道的事情感到抱歉。至于这个问题,就在你推送到状态之前..做一个查找,如果你找到跳过推送...a Array.findIndex((i)=>{ return children.id === currentchild.id})你应该很高兴
  • 考虑使用 Set 而不是 Array :他们的 add 方法对于给定参数是幂等的
  • students.push(this.state.allStudent[idx]) 更改为!students.includes(this.state.allStudent[idx]) && students.push(this.state.allStudent[idx])

标签: javascript arrays reactjs push


【解决方案1】:

当您使用 React 时,您应该能够安全地使用 ES6 Set Object,它可以让您存储任何类型的唯一值。 (https://devdocs.io/javascript/global_objects/set)。

例如

handleSubmit(){

let students = []
for(let idx in this.state.checked){
    if(this.state.checked[idx] ){
        students.push(this.state.allStudent[idx])
    }
}

students = [...new Set(students)];

console.log('students', students)
this.setState({
    studentList: update(this.state.studentList, {$push: students})
})

}

【讨论】:

    【解决方案2】:

    我不是 React.js 方面的专家,但这似乎是一个简单的问题(仅将唯一元素推送到 JS 数组)。您修改如下的函数应该可以工作:

    handleSubmit(){
        let students = [...this.state.studentList];
        for(let idx in this.state.checked){
            if(this.state.checked[idx] && (students.indexOf(this.state.checked[idx]) === -1)){
                students.push(this.state.allStudent[idx])
            }
        }
        console.log('students', students)
        this.setState({
            studentList: update(this.state.studentList, students)
        })
    }
    

    我们在这里所做的基本上是使用 'students' 数组上的 'indexOf()' 方法来检查当前元素是否存在于数组中 - 如果在数组中找不到元素,则 indexOf() 方法返回 -1数组。希望这会有所帮助!

    【讨论】:

    • 是的,这完全是我的想法。但它仍然会抛出“flattenChildren(...): Encountered two children with the same key”错误。我不知道为什么。
    猜你喜欢
    • 1970-01-01
    • 2019-04-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-05-11
    • 1970-01-01
    相关资源
    最近更新 更多