close
在React中使用擴展語法,將元素添加到state數組中。比如說,setNames(current => [...current, 'Carl'])。擴展語法會解包state數組中現存的元素,到一個新數組中。我們可以在其中添加其他元素。
import{useState}from'react';exportdefaultfunctionApp(){const[names,setNames]=useState(['Alice','Bob']);consthandleClick=()=>{//👇️pushtoendofstatearraysetNames(current=>[...current,'Carl']);//👇️spreadanarrayintothestatearray//setNames(current=>[...current,...['Carl','Delilah']]);//👇️pushtobeginningofstatearray//setNames(current=>['Zoey',...current]);};return(<div><div><buttononClick={handleClick}>Pushtostatearray</button></div>{names.map((element,index)=>{return(<divkey={index}><h2>{element}</h2></div>);})}</div>);}
這裡我們使用useState鈎子來管理state數組。注意,我們給setState傳遞了一個函數,因為函數會保證以當前(最新的)狀態調用。
setNames(current=>[...current,'Carl']);當使用前一個狀態計算下一個狀態時,向setState傳遞一個函數。
否則,如果我們所訪問的state數組不代表最新的值,我們可能會得到一些奇怪的競態條件。
我們使用擴展運算符語法,來將已有數組中的元素解包到新數組中。
constarr=['Alice','Bob'];constarr2=[...arr,'Carl'];console.log(arr2);//👉️['Alice','Bob','Carl']上面的例子創建了一個原始數組的淺複製。在React中,不允許修改原始state數組,因此我們不能直接使用push()方法。
添加對象請注意,這種方法也可以用來將一個對象推送到一個state數組。
import{useState}from'react';exportdefaultfunctionApp(){constinitialState=[{id:1,name:'Alice'},{id:2,name:'Bob'},];const[employees,setEmployees]=useState(initialState);consthandleClick=()=>{//👇️pushobjecttoendofstatearraysetEmployees(current=>[...current,{id:3,name:'Carl'}]);//👇️spreadanarrayofobjectsintothestatearray//setEmployees(current=>[//...current,//...[//{id:3,name:'Carl'},//{id:4,name:'Delilah'},//],//]);//👇️pushobjecttobeginningofstatearray//setEmployees(current=>[{id:3,name:'Zoey'},...current]);};return(<div><div><buttononClick={handleClick}>Pushtostatearray</button></div>{employees.map((element,index)=>{return(<divkey={index}><h2>{element.name}</h2></div>);})}</div>);}同樣的方法可以用來將一個對象推送到一個state數組。我們只需將state數組中的元素解包到一個新數組中,並添加指定的對象即可。
參考資料https://bobbyhadz.com/blog/react-push-to-state-array:https://bobbyhadz.com/blog/react-push-to-state-array
[2]Borislav Hadzhiev:https://bobbyhadz.com/about


全站熱搜