在?React?中如何從狀態(tài)數(shù)組中刪除一個元素
在 React 中從狀態(tài)數(shù)組中刪除一個元素:
- 使用
filter()方法迭代數(shù)組。 - 在每次迭代中,檢查是否滿足條件。
- 將狀態(tài)設(shè)置為過濾器方法返回的新數(shù)組。
import {useState} from 'react';
export default function App() {
const initialState = [
{id: 1, name: 'Fql', country: 'Austria'},
{id: 2, name: 'Jiyik', country: 'China'},
];
const [employees, setEmployees] = useState(initialState);
const removeSecond = () => {
setEmployees(current =>
current.filter(employee => {
// ??? 刪除等于 2 的對象
return employee.id !== 2;
}),
);
};
return (
<div>
<button onClick={removeSecond}>Remove second</button>
{employees.map(({id, name, country}) => {
return (
<div key={id}>
<h2>name: {name}</h2>
<h2>country: {country}</h2>
<hr />
</div>
);
})}
</div>
);
}

我們使用 useState 掛鉤初始化了一個員工狀態(tài)變量。
我們傳遞給 Array.filter 方法的函數(shù)會針對數(shù)組中的每個元素進(jìn)行調(diào)用。
在每次迭代中,我們檢查對象的 id 屬性是否不等于 2 并返回結(jié)果。
const initialState = [
{id: 1, name: 'Fql', country: 'Austria'},
{id: 2, name: 'Jiyik', country: 'China'},
];
const filtered = initialState.filter(obj => {
// ??? 為所有 id 不等于 2 的元素返回真
return obj.id !== 2;
});
// ??? [{id: 1, name: 'Fql', country: 'Austria'}]
console.log(filtered);filter 方法返回一個新數(shù)組,其中僅包含回調(diào)函數(shù)返回真值的元素。
如果從未滿足條件,
Array.filter函數(shù)將返回一個空數(shù)組。
我們將一個函數(shù)傳遞給 setState,因為該函數(shù)可以保證以當(dāng)前(最新)狀態(tài)調(diào)用。
const removeSecond = () => {
// ??? current 是當(dāng)前狀態(tài)數(shù)組
setEmployees(current =>
current.filter(employee => {
return employee.id !== 2;
}),
);
};當(dāng)使用前一個狀態(tài)計算下一個狀態(tài)時,將一個函數(shù)傳遞給 setState。
永遠(yuǎn)不要在 React 中改變狀態(tài)數(shù)組
你不應(yīng)該使用像 Array.pop() 或 Array.splice() 這樣的函數(shù)來改變 React 中的狀態(tài)數(shù)組。
const removeSecond = () => {
const index = employees.findIndex(emp => emp.id === 2)
// ?? 不要這樣做
employees.splice(index, 1)
// ?? 或者這樣也不好
employees.pop()
};狀態(tài)對象和數(shù)組是不可變的。 為了讓 React 跟蹤變化,我們需要將狀態(tài)設(shè)置為一個新數(shù)組,而不是修改原始數(shù)組。
根據(jù)多個條件從狀態(tài)數(shù)組中刪除元素
如果我們需要根據(jù)多個條件從狀態(tài)數(shù)組中刪除一個對象,請使用邏輯與 && 或邏輯或 || 運(yùn)算符。
使用邏輯與 (&&) 運(yùn)算符
邏輯與 && 運(yùn)算符檢查多個條件是否為真。
const initialState = [
{id: 1, name: 'Fql', country: 'Austria'},
{id: 2, name: 'Jiyik', country: 'China'},
{id: 3, name: 'Carl', country: 'Austria'},
];
const [employees, setEmployees] = useState(initialState);
const remove = () => {
setEmployees(current =>
current.filter(employee => {
return employee.id !== 3 && employee.id !== 2;
}),
);
};邏輯與 && 運(yùn)算符僅在兩個條件都為真時才計算為真。
僅當(dāng)對象的 id 屬性不等于 3 且不等于 2 時,回調(diào)函數(shù)才返回 true。
使用邏輯或 (||) 運(yùn)算符
邏輯 OR || 運(yùn)算符檢查是否至少有一個條件的計算結(jié)果為真。
const initialState = [
{id: 1, name: 'Fql', country: 'Austria'},
{id: 2, name: 'Jiyik', country: 'China'},
{id: 3, name: 'Carl', country: 'Austria'},
];
const [employees, setEmployees] = useState(initialState);
const remove = () => {
setEmployees(current =>
current.filter(employee => {
return employee.id !== 3 && employee.id !== 2;
}),
);
};兩個條件中的任何一個都必須評估為要添加到新數(shù)組的元素的真值。
換句話說,如果對象的 name 屬性等于 Fql 或 Carl,則該對象將被添加到新數(shù)組中。 所有其他對象都從數(shù)組中過濾掉。
使用兩個運(yùn)算符從狀態(tài)數(shù)組中刪除元素
如果我們必須檢查多個復(fù)雜條件,也可以同時使用這兩種運(yùn)算符。
const initialState = [
{id: 1, name: 'Fql', country: 'Austria'},
{id: 2, name: 'Jiyik', country: 'China'},
{id: 3, name: 'Carl', country: 'Austria'},
];
const [employees, setEmployees] = useState(initialState);
const remove = () => {
setEmployees(current =>
current.filter(employee => {
return employee.name === 'Fql' || employee.name === 'Carl';
}),
);
};
括號中的代碼使用邏輯 OR || 運(yùn)算符來檢查 employee 對象的 name 屬性是否是兩個值之一。
const remove = () => {
setEmployees(current =>
current.filter(employee => {
return (
(employee.name === 'Fql' ||
employee.name === 'Carl') &&
employee.country === 'Canada'
);
}),
);
};如果滿足條件,則邏輯與 && 運(yùn)算符檢查對象的國家/地區(qū)屬性是否等于加拿大。
括號中的表達(dá)式必須計算為真,右側(cè)的條件必須計算為真才能將對象保存在狀態(tài)數(shù)組中。
從 React 中的 State 數(shù)組中刪除重復(fù)項
要從狀態(tài)數(shù)組中刪除重復(fù)項:
- 使用
useState()掛鉤將數(shù)組存儲在狀態(tài)中。 - 使用
Set()構(gòu)造函數(shù)從狀態(tài)數(shù)組中刪除重復(fù)項。 - 將狀態(tài)數(shù)組更新為新值。
import {useState} from 'react';
const App = () => {
const words = ['fql', 'fql', 'jiyik', 'jiyik', 'com'];
const [state, setState] = useState(words);
const withoutDuplicates = [...new Set(words)];
// ??? ['fql', 'jiyik', 'com']
console.log(withoutDuplicates);
const removeDuplicates = () => {
setState(prevState => [...new Set(prevState)]);
};
return (
<div>
<button onClick={removeDuplicates}>
Remove duplicates
</button>
{state.map((word, index) => {
return (
<div key={index}>
<h2>{word}</h2>
</div>
);
})}
</div>
);
};
export default App;

我們傳遞給 Set 構(gòu)造函數(shù)的參數(shù)是一個可迭代的——在我們的例子中是一個數(shù)組。
const words = ['fql', 'fql', 'jiyik', 'jiyik', 'com'];
// ??? {'fql', 'jiyik', 'com'}
console.log(new Set(words));
const withoutDuplicates = [...words];
console.log(withoutDuplicates); // ??? ['fql', 'jiyik', 'com']!> 數(shù)組的所有元素都添加到新創(chuàng)建的集合中。 但是,Set 對象只能存儲唯一值,因此會自動刪除所有重復(fù)項。
最后一步是使用 Spread 運(yùn)算符 ... 將 Set 的值解包到一個新數(shù)組中。
從 React 中的狀態(tài)數(shù)組中刪除重復(fù)對象
要從 React 中的狀態(tài)數(shù)組中刪除重復(fù)對象:
- 創(chuàng)建一個將存儲唯一對象 ID 的空數(shù)組。
- 使用 filter() 方法迭代狀態(tài)數(shù)組。
- 檢查唯一 ID 數(shù)組是否包含當(dāng)前對象的 ID。
- 如果包含 ID,則將對象的 ID 添加到唯一 ID 數(shù)組并將對象添加到狀態(tài)數(shù)組。
import {useState} from 'react';
const App = () => {
const employees = [
{id: 1, name: 'Fql'},
{id: 1, name: 'Fql'},
{id: 2, name: 'Jiyik'},
{id: 2, name: 'Jiyik'},
];
const [state, setState] = useState(employees);
const handleClick = () => {
const uniqueIds = [];
setState(currentState => {
return currentState.filter(element => {
const isDuplicate = uniqueIds.includes(element.id);
if (!isDuplicate) {
uniqueIds.push(element.id);
return true;
}
return false;
});
});
};
return (
<div>
<button onClick={handleClick}>
Remove duplicate objects
</button>
{state.map((employee, index) => {
return (
<div key={index}>
<h2>id: {employee.id}</h2>
<h2>name: {employee.name}</h2>
</div>
);
})}
</div>
);
};
export default App;

我們傳遞給 Array.filter 方法的函數(shù)被數(shù)組中的每個元素(對象)調(diào)用。
const employees = [
{id: 1, name: 'Fql'},
{id: 1, name: 'Fql'},
{id: 2, name: 'Jiyik'},
{id: 2, name: 'Jiyik'},
];
const uniqueIds = [];
const uniqueEmployees = employees.filter(element => {
const isDuplicate = uniqueIds.includes(element.id);
if (!isDuplicate) {
uniqueIds.push(element.id);
return true;
}
return false;
});
console.log(uniqueEmployees);在每次迭代中,我們檢查唯一 ID 數(shù)組是否包含當(dāng)前對象的 ID。
如果是這樣,我們有一個副本。
如果不包含它,我們需要將 ID 添加到唯一 ID 數(shù)組并從函數(shù)返回一個真值。
如果傳遞給該方法的函數(shù)返回真值,則過濾器方法只會向結(jié)果數(shù)組添加一個元素。
uniqueEmployees 數(shù)組不包含任何重復(fù)項。
我們使用 id 屬性作為對象的標(biāo)識符。 但是,在您的情況下,對象的標(biāo)識符可能被稱為其他名稱。
本質(zhì)上,我們的解決方案是:
- 僅將唯一 ID 添加到
uniqueIds數(shù)組。 - 如果對象的 ID 不在
uniqueIds數(shù)組中,則僅將對象添加到結(jié)果數(shù)組。
到此這篇關(guān)于在 React 中從狀態(tài)數(shù)組中刪除一個元素的文章就介紹到這了,更多相關(guān)React 狀態(tài)數(shù)組刪除一個元素內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
React源碼state計算流程和優(yōu)先級實(shí)例解析
這篇文章主要為大家介紹了React源碼state計算流程和優(yōu)先級實(shí)例解析,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪2022-11-11
react項目升級報錯,babel報錯,.babelrc配置兼容等問題及解決
這篇文章主要介紹了react項目升級報錯,babel報錯,.babelrc配置兼容等問題及解決方案,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教2022-08-08
React如何解決fetch跨域請求時session失效問題
這篇文章主要給大家介紹了關(guān)于React如何解決fetch跨域請求時session失效問題的相關(guān)資料,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2018-11-11
使用React+ts實(shí)現(xiàn)無縫滾動的走馬燈詳細(xì)過程
這篇文章主要給大家介紹了關(guān)于使用React+ts實(shí)現(xiàn)無縫滾動的走馬燈詳細(xì)過程,文中給出了詳細(xì)的代碼示例以及圖文教程,對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友可以參考下2023-08-08
create-react-app中添加less支持的實(shí)現(xiàn)
這篇文章主要介紹了react.js create-react-app中添加less支持的實(shí)現(xiàn),文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2019-11-11

