如何使用反应钩子设置状态数组 [英] how to set state array using react hooks
本文介绍了如何使用反应钩子设置状态数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
提前致谢.我有一个如下的状态数组.
Thanks in advance. I have a state array as below.
我需要向状态数组添加一个项目,我发现我们不需要进行状态突变.我如何使用 prevState 设置状态.
I need to add an item to state array, I came across that we need not do state mutation. How do i set state with prevState.
const [messages, setMessages] = React.useState(
[
{
_id: 12,
createdAt: new Date(),
text: 'All good',
user: {
_id: 1,
name: 'Sian Pol',
}
},
{
_id: 21,
createdAt: "2019-11-10 22:21",
text: 'Hello user',
user: {
_id: 2,
name: 'User New'
}
}]
)
如何调用 set State 来附加这个 state 数组.
How to to i call the set State to append this state array.
类似的东西?
setMessages(previousState => ({...stat
谁能帮我获取上面的行代码.
Can anyone help me in getting the above line code.
推荐答案
在列表末尾插入新元素
const addMessage = (newMessage) => setMessages(state => [...state, newMessage])
在列表的开头插入新元素
To insert new element at the begining of the list
const addMessage = (newMessage) => setMessages(state => [newMessage, ...state])
这篇关于如何使用反应钩子设置状态数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文