简体   繁体   English

如何根据复选框更改嵌套对象值?

[英]How to change nested object values based on checkboxes?

I have a checkbox for filters of products.我有一个产品过滤器复选框。 What I want is to change the value of checked when click from false to true or vice-versa.我想要的是在单击时将选中的值从 false 更改为 true,反之亦然。 I have defined a handleChangeChecked function to perform this operation which takes two arguments.我已经定义了一个 handleChangeChecked 函数来执行这个需要两个参数的操作。

 const [Filters, setFilters] = useState([
        {
            id: 'brand',
            name: 'Brands',
            options: [
                { value: 'Casio', label: 'Casio', checked: false },
                { value: 'Yamaha', label: 'Yamaha', checked: false },
            ],
        },
        {
            id: 'size',
            name: 'No of Keys',
            options: [
                { value: 32, label: '32 Keys', checked: false },
                { value: 37, label: '37 Keys', checked: false },
                { value: 44, label: '44 Keys', checked: false },
                { value: 49, label: '49 Keys', checked: false },
                { value: 61, label: '61 Keys', checked: false },
                { value: 76, label: '76 Keys', checked: false },
            ],
        }

    ]


const handleChangeChecked = (section, value) => {
    console.log(section,value)      //brand Casio  (if I click on Casio Checkbox)
}

How can I achieve this functionality?我怎样才能实现这个功能?

You have some other issues here in that the static data which does not change really shouldn't be in React state.您在这里还有一些其他问题,即不会更改的静态数据实际上不应该处于 React 状态。 Updating deep state is perfectly doable but also unnecessarily complex in this use case (unless there's more to it I don't know about).更新深度状态是完全可行的,但在这个用例中也不必要地复杂(除非还有更多我不知道的内容)。

However, maybe it comes from the server or something and that's why your example code does what it does -- so I'm going to ignore that for now in case.但是,也许它来自服务器或其他东西,这就是您的示例代码执行它的原因 - 所以我现在将忽略它以防万一。

To update deep like this I'd highly recommend using Immer .要像这样深入更新,我强烈建议使用Immer Its quite dirty without it because in React you have to do it by creating new state from the old one without mutating the original (which is a big React no-no).没有它会很脏,因为在 React 中你必须通过从旧状态创建新状态而不改变原始状态来做到这一点(这是一个很大的 React 禁忌)。 Immer takes that complexity away for you. Immer 为您消除了这种复杂性。

I'm also assuming the variable section is the same as the ID of each filter.我还假设变量section与每个过滤器的 ID 相同。

import produce from "immer"

// ... rest of code

const handleChangeChecked = (section, value) => {
    setFilters( produce((draft) => {
        const sectionToChange = draft.find((filter) => filter.id === section)
        const option = sectionToChange.options.find(option => option.value === value)
        option.checked = !option.checked
      }))
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM