我正在制作一個 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 更新此物件
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陣列中的特定物件。
uj5u.com熱心網友回復:
我相信您的類別作為類別物件的陣列開始生命,并且您打算將其設定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(...)但這會使對類別進行排序變得更加困難,因為沒有像陣列那樣的物件鍵/值的固定順序。
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/369181.html
標籤:javascript 反应 反应钩子 使用状态
