问题
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});
}
回答1:
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});
}
回答2:
Let's say you have an object like this.
foo : {
bar : "x"
}
To create an array, simply initialize it to an empty array.
foo.newArray = []
If you console.log(foo)
, you will now see this
foo : {
bar : "x",
newArray : []
}
This means your foo
object has an empty array called newArray
. You can add elements to it using the push()
method.
Push a variable like this foo.newArray.push(myVariable);
Push a string like this foo.newArray.push("myString");
Push an object like this
foo.newArray.push({
"bar2" : "val2"
});
For more information on arrays check W3schools
In your particular case, just do ARTICLES.push({})
来源:https://stackoverflow.com/questions/38306219/javascript-creating-array-in-object-and-push-data-to-the-array