本文介绍了JavaScript在对象中创建数组并将数据推送到数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我是编程新手.我正在尝试React并具有addComment函数,该函数在用户向新闻添加评论时执行.此刻我需要创建一个属性 comments (数组)并将其分配或推送到该数组 inputCommentValue 值.但是现在我只重写数组的0元素,并且不能添加新元素.您能告诉我在哪里放置推送方法吗?谢谢!
I'm new to programming. I'm trying React and have function addComment which is executed when a user adds a comment to news.I need to create in this moment a property comments (array) and assign or push to this array inputCommentValue value. But right now I only rewrite 0 element of the array and can't add a new element.Can you please tell me where to put push method? Thank you!
var ARTICLES = [{
title: "sit amet erat",
text: "nam dui proin leo odio porttitor id consequat in consequat ut nulla sed accumsan"
}, {
title: "pulvinar sed",
text: "velit id pretium iaculis diam erat fermentum justo nec condimentum"
}]
addComment(index, inputCommentValue){
ARTICLES = [...ARTICLES], ARTICLES[index].comments=[inputCommentValue];
this.setState({ARTICLES:ARTICLES});
}
推荐答案
假定数据以组件的状态存在,则处理程序将看起来像这样
assuming that data exist in component's state , then handler will look something like that
addComment(index, inputCommentValue){
// copy array , for not mutate state
let ARTICLES = [...this.state.ARTICLES];
// check if comments not exist
if(!ARTICLES[index].comments) ARTICLES[index].comments=[];
// add new comment to array
ARTICLES[index].comments.push(inputCommentValue);
// update component with new articles
this.setState({ARTICLES:ARTICLES});
}
这篇关于JavaScript在对象中创建数组并将数据推送到数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!