[英]how to set a nested object in React Hooks
我正在處理一個表單,其中包含一個部分,用戶可以在其中從下拉列表中選擇音樂會門票的數量和類別。 這個組件是動態創建的,它可以有更多的項目(數量+類別)。 類別的下拉列表是相互關聯的。 因此,如果您選擇一個類別,則其他下拉列表的值應設置為相同的選定值。 但我還需要每個類別下拉列表的名稱進行驗證。
這就是我創建類別對象的方式:
const createCategory = () => {
let cat = {}
let nestedCat = {}
for (let it in item) {
for (let bt in item[it].buyertypes) {
cat2[item[it].buyertypes[bt].id] = ''
}
cat[item[it].id] = nestedCat
nestedCat = {}
}
return cat
}
const [category, setCategory] = useState(createCategory());
這是初始對象:
{
9871: { 1: "", 2: "", 3: "" }
9872: { 5: "", 6: "", 8: "" }
}
我如何顯示和處理工單組件
const handleQuantity = e => {
setQuantity({
...quantity,
[e.target.name]: e.target.value
});
}
const handleCategory = e => {
setCategory({
...category,
[e.target.name]: e.target.value
});
}
const ShowData = () => {
let ticketIem = []
for (let it in item) {
for (let bt in item[it].buyertypes) {
let buyerType = item[it].buyertypes[bt]
ticketIem.push({
'price': buyerType.prices, 'catId': item[it].id,
'qntId': item[it].buyertypes[bt].id
})
}
}
return (
<div>
{ticketIem.map((i, index) => (
<div key={index} >
<div>
<label>Number</label>
<select
value={quantity[i.qntId]}
onChange={handleQuantity}
name={i.qntId}
>
<option value={0}>0</option>
<option value={1}>1</option>
</select>
</div>
<div>
<label>Category</label>
<select
value={category[i.catId]}
onChange={handleCategory}
name={i.catId}
>
<option value="">Choose</option>
{categories.map((cat, index) => (
<option key={index} value={cat.id} name={i.qntId}>
{cat.description} {cat.value}
</option>
))}
</select>
</div>
</div>
))}
</div>
)
}
在下拉列表中選擇一個選項后,類別對象將設置為:
{
9871: "11", 9872: "7"
}
但我希望:
{
9871: { 1: "11", 2: "11", 3: "11" }
9872: { 5: "7", 6: "7", 8: "7" }
}
如果要設置特定類別或數量的所有嵌套屬性,則還需要迭代這些嵌套屬性的鍵。 使用Object.keys
獲取嵌套對象鍵的數組,並將它們縮減為一個新對象,並為每個鍵設置新值。
我建議還使用功能狀態更新,因為每次更新都取決於現有/當前狀態,因為它被淺復制到下一個狀態。
const handleQuantity = (e) => {
setQuantity((quantity) => ({
...quantity,
[e.target.name]: Object.keys(quantity[e.target.name]).reduce(
(obj, key) => ({
...obj,
[key]: e.target.value
}),
{}
)
}));
};
const handleCategory = (e) => {
setCategory((category) => ({
...category,
[e.target.name]: Object.keys(category[e.target.name]).reduce(
(obj, key) => ({
...obj,
[key]: e.target.value
}),
{}
)
}));
};
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.