問題描述
如何使用 useState 將許多元素添加到數組中? (How to add many elements to an array with useState?)
這就是向項目添加一個元素的方式
const [items, setItems] = useState
setItems([...items, newElm ]);
但是,如果我想向項目添加/連接一組元素怎麼辦。這不起作用
const [items, setItems] = useState
setItems([...items, newArr ]);
我該怎麼做?
參考解法
方法 1:
You have to spread the new array just as the items array.
Remember that the recommended way to merge the new items
array with your current state is as follows:
setItems(prevState => ([...prevState, ...newArray]))
In this way you can ensure that prevState
will have an updated value.
方法 2:
Spread the elements of the new array into the state
const [items, setItems] = useState setItems([...items, ...newArr ]);
(by Joshua Segal、Ian Vasco、Awotide Isaiah McZenith)