在React对象中添加数据

发布于 2025-02-13 02:59:48 字数 180 浏览 0 评论 0原文

我想让您帮助我做一些对我不好的东西,发生的事情是我想通过功能在数组中添加一个数据,而不是添加它,而是覆盖它,我不知道什么是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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

流星番茄 2025-02-20 02:59:48

首先,您需要添加一个元素,而不是用另一个元素覆盖整个数组。第二个React Usestate变量您应该使用先前的值来更新新数组。您不能使用列表本身。 Try this:

const [list,setList]=useState([])

const addList=(id)=>{
    setList(pre => [...pre, id])
}

Or you can use this (it's in old javascript way):

const [list,setList]=useState([])

const addList=(id)=>{
    let newList = list
    newList.push(id)
    setList(newList)
}

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:

const [list,setList]=useState([])

const addList=(id)=>{
    setList(pre => [...pre, id])
}

Or you can use this (it's in old javascript way):

const [list,setList]=useState([])

const addList=(id)=>{
    let newList = list
    newList.push(id)
    setList(newList)
}
醉梦枕江山 2025-02-20 02:59:48

我认为您想要这样的东西,将ID附加到list数组:

const [list,setList]=useState([])
const addList=(id)=>{
    setList([...list, id])
}

I think you want something like this, which appends id to the list array:

const [list,setList]=useState([])
const addList=(id)=>{
    setList([...list, id])
}

对你的占有欲 2025-02-20 02:59:48

当您使用其先前的值更新React State属性(例如list)时,
您应该使用SetState的回调参数。
原因是状态更新可能在react中具有异步性( https://reactjs.org/docs/state-and-lifecycle.html#state-updates-updates-may-be-be-asynchronous

const [list,setList]=useState([])
const addList=(id)=>{
    setList(list=> list.concat(id));
    // or setList(list=> [...list, id]);
})
}

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)

const [list,setList]=useState([])
const addList=(id)=>{
    setList(list=> list.concat(id));
    // or setList(list=> [...list, id]);
})
}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文