【问题标题】:How do I not include duplicate values in a React state array , how to prevent duplication of values in array?如何在 React 状态数组中不包含重复值,如何防止数组中的值重复?
【发布时间】:2021-08-18 09:53:01
【问题描述】:

我想在 items[0].question state 中存储 15 个不同的问题

我想确保我不能将重复值推送到 React 状态的数组中。重复的值仍在数组中。

我尝试过使用 .includes 但它不起作用。

const [exam, setExam] = useState({
    subjectName: "",
    questions: [

    ], notes: [
        ""
    ]
})

const [item, setItem] = useState([
    {
        question: "",
        answer: "",
        options: []
    }
])

const nextQuestion = (e) => {
    e.preventDefault()
    const que = item[0].question

    exam?.questions?.push({ question: que, answer: value, options: [item[0].options[1], item[0].options[2], item[0].options[3], item[0].options[4]] })

}

【问题讨论】:

    标签: arrays reactjs duplicates use-state arrayofarrays


    【解决方案1】:

    因为你使用的是setState,你需要使用setExam来更新exam

    类似:

    const newQuestion = { question: que, answer: value, options: [item[0].options[1], item[0].options[2], item[0].options[3], item[0].options[4]] }
    newExams = {...exam, questions: [...exam.questions, newQuestion ]}
    setExam(newExams)
    

    【讨论】:

    • 这已完成,但我想添加没有重复值的问题和选项,在这种情况下重复值也被推送
    • 这将帮助您避免在问题列表中添加重复项if (exam?.questions.every(x=> !(x['que']== que))){ //Answer }
    • 你可以这样做来删除重复的选项let options = [item[0].options[1], item[0].options[2], item[0].options[3], item[0].options[4]] let optionsWithNoDuplicates = Object.keys(options.reduce((a,c) => ({...a,[c]: (a[c] || 0) + 1}),{})) const newQuestion = { question: que, answer: value, options: optionsWithNoDuplicates }
    猜你喜欢
    • 2019-09-23
    • 1970-01-01
    • 1970-01-01
    • 2021-09-23
    • 2020-01-24
    • 1970-01-01
    • 1970-01-01
    • 2018-07-10
    • 2012-11-09
    相关资源
    最近更新 更多