简体   繁体   English

如何更新reactjs中的对象数组

[英]how to update array of objects in reactjs

i have a state(array of object) which is as follows:我有一个状态(对象数组),如下所示:

 const [state,setstate]=useState({picture:'',name:'',job:''})

and i have 3 inputs in Front-end side which get picture,name,job... i define an array to save a collection of objects (consisting of picture,name and job of each person) as follows:我在前端有 3 个输入,它们获取图片、姓名、工作...我定义了一个数组来保存对象集合(由每个人的图片、姓名和工作组成),如下所示:

 var colllection=[]

i use collection.push({state}) , but it overrides collection and does not add new state to end of the mentioned array.any idea?我使用 collection.push({state}) ,但它覆盖了集合并且不会在提到的数组末尾添加新状态。有什么想法吗?

For react state you need to replace the value rather than changing it.对于反应状态,您需要替换该值而不是更改它。

So code something like this:所以编码是这样的:

const [state, setstate] = useState([]);

const handleAddPerson = person => useState(prev => ([...prev, person]));

Where when we want to add a person we set the state to a new array that contains the contents of the original array plus the new object.当我们想要添加一个人时,我们将状态设置为一个新数组,该数组包含原始数组的内容和新对象。

useState rather than being passed a new value can be passed a function which takes as an argument the previous value the state held and returns the new value for the state. useState而不是传递一个新值可以传递一个函数,该函数将状态保持的先前值作为参数并返回状态的新值。

I'm used to syntactic sugar for creating a new array [...prev, person] this could be written in plain javascript as prev.concat([person]) .我习惯于使用语法糖来创建一个新数组[...prev, person]这可以用普通的 javascript 编写为prev.concat([person])

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM