【发布时间】:2019-05-10 00:34:02
【问题描述】:
我有一个类似帖子的应用程序,用户可以在帖子中添加带有表情符号的 cmets,我有一个方法:
addEmoji = (newEmoji) =>{
// mark if new emoji is already in the array or not
let containsNewEmoji = false;
let authors = []
authors.push(this.props.comment.author.name)
console.log(this.props.comment.author.name)
console.log(authors)
// recreate emojis array
let newEmojis = this.state.emojis.map(emoji => {
// if emoji already there, simply increment count
if (emoji.id === newEmoji.id) {
containsNewEmoji = true;
return {
...newEmoji,
...emoji,
count: emoji.count + 1,
authors: [...authors, authors]
};
}
// otherwise return a copy of previous emoji
return {
...emoji
};
});
console.log(authors)
// if newEmoji was not in the array previously, add it freshly
if (!containsNewEmoji) {
newEmojis = [...newEmojis, {...newEmoji, count: 1, authors: [...authors, authors]}];
}
// set new state
this.setState({ emojis: newEmojis,
showEmoji: true});
}
如代码中的方法 cmets 所示,每个表情符号仅显示一次,否则,计数变量将增加,显示在每个注释下方。
我想添加该功能,以保存添加表情符号的人的给定用户名数组。
用户名作为道具给出
this.props.comment.author.name
所以我尝试制作一个数组来添加名称 7
let authors = []
authors.push(this.props.comment.author.name)
问题是每次传递新的表情符号实例时都会被覆盖,我尝试将其保存到对象中
return {
...newEmoji,
...emoji,
count: emoji.count + 1,
authors: [...authors, authors] // i want to save the old copy of authors and pass the new name
};
newEmojis = [...newEmojis, {...newEmoji, count: 1, authors: [...authors, authors]}]; // and then set the object in the end
到目前为止,数组每次都被覆盖,但我可以在对象内部设置参数吗?
【问题讨论】:
标签: arrays reactjs object nested