![](/img/trans.png)
[英]How to Use One Array of Strings to Filter Another Array of Strings (JS)
[英]How to filter multiple options/strings of an array in one filter?
我正在嘗試實現一個多選下拉菜單,用戶可以在其中進行相應的過濾,例如,如果選擇了Live
和Schedule
,則只應顯示具有這兩個條件的結果。
這是我當前為多選下拉列表過濾 function:
過濾 function & handleChange
const displayBulletins = bulletins
.filter((bulletin) => {
if (optionSelected === '') {
return bulletin
} else if (bulletin.liveStatus.toLowerCase().includes(optionSelected.map(item => item.value))) {
return bulletin
}
return false
})
const handleChange = selected => {
setOptionSelected(selected)
console.log(selected, '--optionsSelected')
console.log(selected.map(item => item.value), '--mappedOptionsSelected')
};
我當前的問題是,如果我只selected 1 of the live status
選項,則過濾有效,但如果我選擇了多個選項,它就不起作用,而是什么也不會過濾掉,所以我想要實現的目標這是為了使其適用於多種選擇,例如["live", "schedule"]
在這種情況下或所有 3 種情況。
這是我的代碼沙箱供參考:
過濾器的回調應如下所示:
filter((bulletin) => {
if (optionSelected.length === 0) {
return true;
} else {
return optionSelected
.map((item) => item.value)
.includes(bulletin.liveStatus.toLowerCase());
}
})
因為您必須檢查optionSelected
數組是否具有liveStatus
而不是相反。
這是更新后的 CodeSandbox:
順便說一句,在 function 組件的主體中定義 function 組件會導致不必要的重新渲染。 在react-select
的情況下,它會導致焦點問題,這就是為什么在外部單擊時下拉菜單沒有關閉的原因。
這里的問題是optionsSelected
是一個數組, bulletin.liveStatus
是一個數組,所以需要查看liveStatus
是否在optionsSelected
數組中
我在代碼沙箱中修改了以下內容並且它起作用了。
另外,不要忘記添加一個帶有鍵而不是 <> 的片段,以允許 React 在重新渲染虛擬 DOM 時表現良好。
如果你想在沒有選擇任何選項的情況下顯示所有公告,而不是返回false
,你應該返回true
const displayBulletins = bulletins
.filter((bulletin) => {
if (optionSelected === []) {
return bulletin;
} else if (
optionSelected
.map((item) => item.value)
.includes(bulletin.liveStatus.toLowerCase())
) {
return bulletin;
}
return false;
})
.map((bulletin) => {
return (
<Fragment key={bulletin.bbID}>
<BulletinList
bulletin={bulletin}
onDelete={onDelete}
/>
</Fragment>
);
});
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.