您好,登錄后才能下訂單哦!
本文小編為大家詳細(xì)介紹“React中怎么從狀態(tài)數(shù)組中刪除一個(gè)元素”,內(nèi)容詳細(xì),步驟清晰,細(xì)節(jié)處理妥當(dāng),希望這篇“React中怎么從狀態(tài)數(shù)組中刪除一個(gè)元素”文章能幫助大家解決疑惑,下面跟著小編的思路慢慢深入,一起來學(xué)習(xí)新知識(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 的對(duì)象 return employee.id !== 2; }), ); }; return ( <div> <button onClick={removeSecond}>Remove second</button> {employees.map(({id, name, country}) => { return ( <div key={id}> <h3>name: {name}</h3> <h3>country: {country}</h3> <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
。
你不應(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)對(duì)象和數(shù)組是不可變的。 為了讓 React 跟蹤變化,我們需要將狀態(tài)設(shè)置為一個(gè)新數(shù)組,而不是修改原始數(shù)組。
如果我們需要根據(jù)多個(gè)條件從狀態(tài)數(shù)組中刪除一個(gè)對(duì)象,請(qǐng)使用邏輯與 &&
或邏輯或 ||
運(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。
邏輯 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ù)組的元素的真值。
換句話說,如果對(duì)象的 name 屬性等于 Fql 或 Carl,則該對(duì)象將被添加到新數(shù)組中。 所有其他對(duì)象都從數(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)算符來檢查 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ù)組中。
要從狀態(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}> <h3>{word}</h3> </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ì)象:
創(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}> <h3>id: {employee.id}</h3> <h3>name: {employee.name}</h3> </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ù)返回真值,則過濾器方法只會(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ù)組。
讀到這里,這篇“React中怎么從狀態(tài)數(shù)組中刪除一個(gè)元素”文章已經(jīng)介紹完畢,想要掌握這篇文章的知識(shí)點(diǎn)還需要大家自己動(dòng)手實(shí)踐使用過才能領(lǐng)會(huì),如果想了解更多相關(guān)內(nèi)容的文章,歡迎關(guān)注億速云行業(yè)資訊頻道。
免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場(chǎng),如果涉及侵權(quán)請(qǐng)聯(lián)系站長(zhǎng)郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。