在 React 中更新对象数组中的对象 属性 时出现问题

Problem with updating object property in array of objects in React

我正在做一个 ecommrece 项目,在搜索栏中,我显示了 API 类别的复选框,默认情况下所有这些都具有 active == true 的值。这就是我映射它们的方式:

{categories.map((category) => {
       return (
              <>
             <input type="checkbox" onClick={() => handleCheckbox(category)} 
             defaultChecked={category.active} key={category.name} />
             <label style={{marginLeft:"5px"}} htmlFor={category.name}>{category.name}</label><br/>
             </> 
)
})}

然后我 运行 这个函数将 category.active 属性 从 true 更改为 false,当确切的复选框被点击时,我想使用 useState[=15 更新这个对象=]

const handleCheckbox = (category) => {
    let tempCategory = category
    if (tempCategory.active == true) {
        tempCategory.active = false;
    } else {
        tempCategory.active = true;
    }
    setCategories({...categories, [tempCategory.id]: tempCategory})
    console.log(category.active)
}

不幸的是,当我点击复选框时,我收到来自 React 的错误:

TypeError: categories.map is not a function

它指向 categories.map,我不知道如何修复它。我只想更新 categories 数组中的特定对象。

我相信您的类别最初是作为类别对象的数组开始的,您打算 setCategories 到一个数组 - 但您却将其设置为一个对象。

你还需要确保你没有加倍 tempCategory。像这样:

setCategories([
 ...categories.filter(x => x.id != tempCategory.id), 
 tempCategory
]);

但是,这会重新排序您的类别,将 tempCategory 放在末尾,因此另一种选择是正确分割数组

const tmpIdx = categories.findIndex(x => x.id == tempCategory.id);
setCategories([
     ...categories.slice(0,tmpIdx), 
     tempCategory,
     ...categories.slice(tmpIdx+1), 
]);

另一种选择是让您的 categories 成为一个对象并使用 Object.values(categories).map(...) 但这会使您的类别排序变得更加困难,因为对象 keys/values 没有固定的排序数组。