Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/reactjs/27.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 递增数组内对象的计数_Javascript_Reactjs - Fatal编程技术网

Javascript 递增数组内对象的计数

Javascript 递增数组内对象的计数,javascript,reactjs,Javascript,Reactjs,我有一个在ReactJS中生成表情的函数 addEmoji = (emoji) =>{ //with array function let newEmoji = { id: emoji.id, count: 1 }; if(this.state.emojis.filter(emoji =>{ if(emoji.id === newEmoji.id){ this.increment(newEmoji); } }))

我有一个在ReactJS中生成表情的函数

addEmoji = (emoji) =>{

  //with array function


 let newEmoji = {
    id: emoji.id,
    count: 1
  };
  if(this.state.emojis.filter(emoji =>{
    if(emoji.id === newEmoji.id){
      this.increment(newEmoji);
    }
  }))
  console.log(this.state.emojis)
  this.setState( prevState => ({
    emojis: [...prevState.emojis, newEmoji],
    showEmoji: true
  }))
它接受来自表情集市节点模块的自定义表情对象

我现在的问题是,我想检查对象是否已经显示,如果已经显示,则增加计数

我做了这个递增的方法,每个表情对象的计数递增。我的问题是我必须改变整个数组中一个对象的状态,这给我带来了困难

increment = (newEmoji) =>{
 console.log(id);

  let count = newEmoji.count
  count = newEmoji.count+1
  console.log(newEmoji.count)
 this.setState(   

   {emoji: newEmoji} // how do i change the state of that one obejct inside the array
 )
 console.log(this.state.emoji.count)
}
编辑: 我已经提供了状态,看有没有状态正在设置

this.state= {
 emojis: []
}

您可以在迭代时重新创建整个数组,并在必要时更改表情符号的计数,一石二鸟。以下是未经测试的版本:

// mark if new emoji is already in the array or not
let containsNewEmoji = false;

// 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,
    };
  }

  // otherwise return a copy of previos emoji
  return {
    ...emoji
  };
});

// if newEmoji was not in the array previously, add it freshly
if (!containsNewEmoji) {
  newEmojis = [...newEmojis, {...newEmoji, count: 0}];
}

// set new state
this.setState({ emojis: newEmojis });

完美的但是,我还需要添加逻辑,以便在同一个函数中最初向数组中添加表情符号?`if(!containsnewmoji){newEmojis=[…newEmojis,newEmoji];}这就解决了,不是吗?好的,我编辑了我的答案,我们还必须用0初始化表情符号的初始计数:
newEmojis=[…newEmojis,{…newEmoji,count:0}它说无法读取undefined的属性0,当我插入新代码时,是因为它无法识别newEmoji对象计数变量吗?我想这是因为它初始化为一个数字到很晚,当它递增时,它仍然是未定义的