[英]Delete multiple elements from List on React Native
當我按下按鈕時,我目前正在嘗試從列表中刪除。 我試過這個:
const [currentSelection, setCurrentSelection] = useState([]);
const [removeSelection, setRemoveSelection] = useState([]);
function handleRemoveMeal() {
currentSelection = setCurrentSelection(currentSelection.filter((item)
=> !removeSelection.includes(item)));
}
但是,我得到一個currentSelection is read-only
錯誤。 我能夠正確存儲 currentSelection 和 removeSelection 中的所有元素,所以我有點卡住了。 如果我能得到一些幫助,我將不勝感激!
編輯:我也嘗試過使用拼接,但我的列表沒有更新。
for (var i = currentSelection.length - 1; i >= 0; i--) {
for (var j = removeSelection.length - 1; j >= 0; j--) {
if (currentSelection[i] == removeSelection[j]) {
setCurrentSelection(currentSelection.splice(i, 1));
}
}
}
編輯2:更多上下文
//meals to choose from
const meals = [
{ label: 'Bangkok Chicken Wrap', value: 21 },
{ label: 'Moo Shu Chicken', value: 25 },
{ label: 'Strawberry Gelatin', value: 43 },
{ label: 'Waffle Fries', value: 20 },
{ label: 'Firehouse Chili with Pork', value: 35 },
{ label: 'Gluten Free Cookies', value: 41 },
{ label: 'Pineapple Chunks', value: 6 },
{ label: 'Vegan Pub Fried Fish', value: 23 },
{ label: 'Brown Rice with Mushrooms', value: 47 },
]
const onFavSelectionsChange = favSelections => {
setRemoveSelection(favSelections);
}
<View>
<View style={ styles.selectMultipleView }>
<SelectMultiple
items={currentSelection}
selectedItems={removeSelection}
onSelectionsChange={onFavSelectionsChange}
/>
</View>
<View style={ [styles.buttonView, {alignItems:"center"}] }>
<Button style={ styles.removeButtonComponent } onPress= { handleRemoveMeal }>
<Text style={ styles.removeButtonText }>Remove</Text>
</Button>
</View>
</View>
setCurrentSelection
完成“設置” currentSelection
的工作(因此命名),所以你不需要用=
來分配它。 只需使用:
function handleRemoveMeal() {
setCurrentSelection(currentSelection.filter(item => !removeSelection.includes(item)));
}
您可能還想在此處使用 use/set state 的回調版本,這樣您就不會得到陳舊的值:
function handleRemoveMeal() {
setCurrentSelection(originalSelection => originalSelection.filter(item => !removeSelection.includes(item)));
}
更新說明 SelectMultiple 返回值的方式:
const handleRemoveMeal = () => {
const filtered = currentSelection.filter(item => !removeSelection.map(i => i.value).includes(item.value));
setCurrentSelection(filtered);
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.