我有兩個選擇串列,我可以從中選擇值
串列一=“A”,“B”
串列二 = "C", "D", "E", "F"
我有一個反應狀態
const [filterTags, setFilterTags] = useState({ one: [], two: [] });
我可以從任何串列中一次傳遞一個 valupdateValue(val)
我需要以這樣的方式更新 filterTags,如果它val來自串列one, A或者B它應該像這樣更新狀態
{one:["A"]: two:[]}
const updateValue = (val) => {
if (val === 'A' || val === 'B') {
setFilterTags({ one: val });
} else {
setFilterTags({ ...filterTags, two: val });
}
};
如果我A C C D B A E C一一通過它應該用唯一值更新陣列,輸出應該是
{one:["A"]: two:[]} //passing A
{one:["A"]: two:["C"]} //passing C
{one:["A"]: two:["C"]} // same since C is already there in two on passing C
{one:["A"]: two:["C","D"]} //passing D
{one:["A","B"]: two:["C","D"]} //passing B
{one:["A","B"]: two:["C","D"]} //same since A is already present in one on //passing A
{one:["A","B"]: two:["C","D","E"]} //passing E
{one:["A","B"]: two:["C","D","E"]}// final output on passing C
它現在應該用唯一值更新相應的元素上面的代碼只能更新一個值
uj5u.com熱心網友回復:
您應該確保只添加不存在的元素,您可以使用includes陣列上的函式進行檢查,并且您還希望確保保留所有以前的內容。
一個潛在的解決方案可能是執行以下操作:
const updateValue = (val) => {
if (val === 'A' || val === 'B') {
if(!filterTags.one.includes(val)) {
setFilterTags((prev) => ({ one: [...prev.one, val], two: prev.two }));
}
} else {
if(!filterTags.two.includes(val)) {
setFilterTags((prev) => ({ one: prev.one, two: [...prev.two, val] }));
}
}
};
uj5u.com熱心網友回復:
此注釋代碼可以幫助您:
const updateValue = (val) => {
//creating a temporary copy of filterTags
const tempFilterTags = {...filterTags}
//checking if val is A or B and if finterTag.one does not contain the value
if ((val === 'A' || val === 'B') && filterTags.one.find(el=> el == val) === null) {
//if success, push the value for field one and update filterTag
tempFilterTags.one.push(val)
setFilterTags(tempFilterTags)
}
//checking if val is C, D, E of F and if finterTag.two does not contain the value
if ((val === 'C' || val === 'D' || val === 'E' || val === 'F') && filterTags.two.find(el=> el == val) === null) {
//if success, push the value for field two and update filterTag
tempFilterTags.two.push(val)
setFilterTags(tempFilterTags)
}
};
uj5u.com熱心網友回復:
在設定狀態時,使用功能更新選項獲取先前的值 ( prev),并使用 spread 使用先前和更新的值創建新狀態。使用 Set 來維護唯一值。
const updateValue = (val) => {
if (val === 'A' || val === 'B') {
setFilterTags(prev => ({ ...prev, one: [...new Set([...prev.one, val])] }));
} else {
setFilterTags(prev => ({ ...prev, two: [...new Set([...prev.two, val])] }));
}
};
怎么這里代碼重復太多了,因為設定狀態的邏輯是一樣的,只是key變了,所以可以重構一下:
const updateValue = (val) => {
const key = val === 'A' || val === 'B' ? 'one' : 'two';
setFilterTags(prev => ({ ...prev, [key]: [...new Set([...prev[key], val])] }));
};
您還可以Array.includes按照Houssam 的建議使用以避免更新狀態:
const updateValue = (val) => {
const key = val === 'A' || val === 'B' ? 'one' : 'two';
setFilterTags(prev => {
const key = val === 'A' || val === 'B' ? 'one' : 'two';
return prev[key].includes(val)
? prev
: { ...prev, [key]: [...prev[key], val] };
});
};
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/329680.html
標籤:javascript 数组 反应 目的 反应钩子
