在React对象中添加数据
我想让您帮助我做一些对我不好的东西,发生的事情是我想通过功能在数组中添加一个数据,而不是添加它,而是覆盖它,我不知道什么是Redux错误:
const [list,setList]=useState([])
const addList=(id)=>{
setList([id])
}
I want you to help me with something that doesn't work well for me, what happens is that I want to add a data in an array through a function but instead of adding it, it overrides it, I don't know what is wrong in redux:
const [list,setList]=useState([])
const addList=(id)=>{
setList([id])
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
首先,您需要添加一个元素,而不是用另一个元素覆盖整个数组。第二个React Usestate变量您应该使用先前的值来更新新数组。您不能使用列表本身。 Try this:
Or you can use this (it's in old javascript way):
First you need to add an element not override the whole array with another one. Second in react useState variable you should use the previous value to update the new array. You can't use the list itself. Try this:
Or you can use this (it's in old javascript way):
我认为您想要这样的东西,将
ID
附加到list
数组:I think you want something like this, which appends
id
to thelist
array:当您使用其先前的值更新React State属性(例如
list
)时,您应该使用SetState的回调参数。
原因是状态更新可能在react中具有异步性( https://reactjs.org/docs/state-and-lifecycle.html#state-updates-updates-may-be-be-asynchronous )
When you update a React state property (like your
list
) using its previous value,you should use the callback argument of setState.
The reason is that state updates may be asynchronous in React (https://reactjs.org/docs/state-and-lifecycle.html#state-updates-may-be-asynchronous)