在?React?中如何從狀態(tài)數(shù)組中刪除一個(gè)元素
在 React 中從狀態(tài)數(shù)組中刪除一個(gè)元素:
- 使用
filter()方法迭代數(shù)組。 - 在每次迭代中,檢查是否滿足條件。
- 將狀態(tài)設(shè)置為過(guò)濾器方法返回的新數(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 的對(duì)象
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 掛鉤初始化了一個(gè)員工狀態(tài)變量。
我們傳遞給 Array.filter 方法的函數(shù)會(huì)針對(duì)數(shù)組中的每個(gè)元素進(jìn)行調(diào)用。
在每次迭代中,我們檢查對(duì)象的 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 方法返回一個(gè)新數(shù)組,其中僅包含回調(diào)函數(shù)返回真值的元素。
如果從未滿足條件,
Array.filter函數(shù)將返回一個(gè)空數(shù)組。
我們將一個(gè)函數(shù)傳遞給 setState,因?yàn)樵摵瘮?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)使用前一個(gè)狀態(tài)計(jì)算下一個(gè)狀態(tài)時(shí),將一個(gè)函數(shù)傳遞給 setState。
永遠(yuǎn)不要在 React 中改變狀態(tài)數(shù)組
你不應(yīng)該使用像 Array.pop() 或 Array.splice() 這樣的函數(shù)來(lái)改變 React 中的狀態(tài)數(shù)組。
const removeSecond = () => {
const index = employees.findIndex(emp => emp.id === 2)
// ?? 不要這樣做
employees.splice(index, 1)
// ?? 或者這樣也不好
employees.pop()
};狀態(tài)對(duì)象和數(shù)組是不可變的。 為了讓 React 跟蹤變化,我們需要將狀態(tài)設(shè)置為一個(gè)新數(shù)組,而不是修改原始數(shù)組。
根據(jù)多個(gè)條件從狀態(tài)數(shù)組中刪除元素
如果我們需要根據(jù)多個(gè)條件從狀態(tài)數(shù)組中刪除一個(gè)對(duì)象,請(qǐng)使用邏輯與 && 或邏輯或 || 運(yùn)算符。
使用邏輯與 (&&) 運(yùn)算符
邏輯與 && 運(yùn)算符檢查多個(gè)條件是否為真。
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)算符僅在兩個(gè)條件都為真時(shí)才計(jì)算為真。
僅當(dāng)對(duì)象的 id 屬性不等于 3 且不等于 2 時(shí),回調(diào)函數(shù)才返回 true。
使用邏輯或 (||) 運(yùn)算符
邏輯 OR || 運(yùn)算符檢查是否至少有一個(gè)條件的計(jì)算結(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;
}),
);
};兩個(gè)條件中的任何一個(gè)都必須評(píng)估為要添加到新數(shù)組的元素的真值。
換句話說(shuō),如果對(duì)象的 name 屬性等于 Fql 或 Carl,則該對(duì)象將被添加到新數(shù)組中。 所有其他對(duì)象都從數(shù)組中過(guò)濾掉。
使用兩個(gè)運(yùn)算符從狀態(tài)數(shù)組中刪除元素
如果我們必須檢查多個(gè)復(fù)雜條件,也可以同時(shí)使用這兩種運(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';
}),
);
};
括號(hào)中的代碼使用邏輯 OR || 運(yùn)算符來(lái)檢查 employee 對(duì)象的 name 屬性是否是兩個(gè)值之一。
const remove = () => {
setEmployees(current =>
current.filter(employee => {
return (
(employee.name === 'Fql' ||
employee.name === 'Carl') &&
employee.country === 'Canada'
);
}),
);
};如果滿足條件,則邏輯與 && 運(yùn)算符檢查對(duì)象的國(guó)家/地區(qū)屬性是否等于加拿大。
括號(hào)中的表達(dá)式必須計(jì)算為真,右側(cè)的條件必須計(jì)算為真才能將對(duì)象保存在狀態(tài)數(shù)組中。
從 React 中的 State 數(shù)組中刪除重復(fù)項(xiàng)
要從狀態(tài)數(shù)組中刪除重復(fù)項(xiàng):
- 使用
useState()掛鉤將數(shù)組存儲(chǔ)在狀態(tài)中。 - 使用
Set()構(gòu)造函數(shù)從狀態(tài)數(shù)組中刪除重復(fù)項(xiàng)。 - 將狀態(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ù)是一個(gè)可迭代的——在我們的例子中是一個(gè)數(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 對(duì)象只能存儲(chǔ)唯一值,因此會(huì)自動(dòng)刪除所有重復(fù)項(xiàng)。
最后一步是使用 Spread 運(yùn)算符 ... 將 Set 的值解包到一個(gè)新數(shù)組中。
從 React 中的狀態(tài)數(shù)組中刪除重復(fù)對(duì)象
要從 React 中的狀態(tài)數(shù)組中刪除重復(fù)對(duì)象:
- 創(chuàng)建一個(gè)將存儲(chǔ)唯一對(duì)象 ID 的空數(shù)組。
- 使用 filter() 方法迭代狀態(tài)數(shù)組。
- 檢查唯一 ID 數(shù)組是否包含當(dāng)前對(duì)象的 ID。
- 如果包含 ID,則將對(duì)象的 ID 添加到唯一 ID 數(shù)組并將對(duì)象添加到狀態(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ù)組中的每個(gè)元素(對(duì)象)調(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)前對(duì)象的 ID。
如果是這樣,我們有一個(gè)副本。
如果不包含它,我們需要將 ID 添加到唯一 ID 數(shù)組并從函數(shù)返回一個(gè)真值。
如果傳遞給該方法的函數(shù)返回真值,則過(guò)濾器方法只會(huì)向結(jié)果數(shù)組添加一個(gè)元素。
uniqueEmployees 數(shù)組不包含任何重復(fù)項(xiàng)。
我們使用 id 屬性作為對(duì)象的標(biāo)識(shí)符。 但是,在您的情況下,對(duì)象的標(biāo)識(shí)符可能被稱為其他名稱。
本質(zhì)上,我們的解決方案是:
- 僅將唯一 ID 添加到
uniqueIds數(shù)組。 - 如果對(duì)象的 ID 不在
uniqueIds數(shù)組中,則僅將對(duì)象添加到結(jié)果數(shù)組。
到此這篇關(guān)于在 React 中從狀態(tài)數(shù)組中刪除一個(gè)元素的文章就介紹到這了,更多相關(guān)React 狀態(tài)數(shù)組刪除一個(gè)元素內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
React源碼state計(jì)算流程和優(yōu)先級(jí)實(shí)例解析
這篇文章主要為大家介紹了React源碼state計(jì)算流程和優(yōu)先級(jí)實(shí)例解析,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪2022-11-11
react項(xiàng)目升級(jí)報(bào)錯(cuò),babel報(bào)錯(cuò),.babelrc配置兼容等問(wèn)題及解決
這篇文章主要介紹了react項(xiàng)目升級(jí)報(bào)錯(cuò),babel報(bào)錯(cuò),.babelrc配置兼容等問(wèn)題及解決方案,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2022-08-08
快速創(chuàng)建React項(xiàng)目并配置webpack
這篇文章主要介紹了創(chuàng)建React項(xiàng)目并配置webpack,在這里需要注意,Create?React?App?requires?Node?14?or?higher.需要安裝高版本的node,本文給大家介紹的非常詳細(xì),需要的朋友參考下吧2022-01-01
React如何解決fetch跨域請(qǐng)求時(shí)session失效問(wèn)題
這篇文章主要給大家介紹了關(guān)于React如何解決fetch跨域請(qǐng)求時(shí)session失效問(wèn)題的相關(guān)資料,文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來(lái)一起學(xué)習(xí)學(xué)習(xí)吧2018-11-11
使用React+ts實(shí)現(xiàn)無(wú)縫滾動(dòng)的走馬燈詳細(xì)過(guò)程
這篇文章主要給大家介紹了關(guān)于使用React+ts實(shí)現(xiàn)無(wú)縫滾動(dòng)的走馬燈詳細(xì)過(guò)程,文中給出了詳細(xì)的代碼示例以及圖文教程,對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友可以參考下2023-08-08
create-react-app中添加less支持的實(shí)現(xiàn)
這篇文章主要介紹了react.js create-react-app中添加less支持的實(shí)現(xiàn),文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來(lái)一起學(xué)習(xí)學(xué)習(xí)吧2019-11-11

