如何保持阵列的内部对象的指数?

问题描述 投票:0回答:1

我试图在反应码“blockchain”视觉实现。我想拥抱的对象莫名其妙内部阵列(是我的块)每个对象的索引。我无法弄清楚如何做到这一点。

    this.state = {
      value: '',
      blocks: [{
        hash: calculateHash(1),
        timestamp: timeStamp(),
        dataOfBlock: 'Genesis Block',
        nounce: 607,
        index: 0
      }]
    }
  };

    addBlock = (event) => {
      event.preventDefault();

      this.setState({
      blocks: [...this.state.blocks, {
        hash: 'cos',
        timestamp: timeStamp(),      
        dataOfBlock: this.state.value,
        nounce: '',
        index: 1 // here's the problem
      }]
    })
    }

我的代码模仿什么我要完成其中的评论是。我要不断地添加+1到我的每块索引。

javascript reactjs
1个回答
4
投票

添加新对象时,可以使用length作为新对象的索引 注:this.state.blocks.length将在未来的指数,因为指数从0启动

blocks: [...this.state.blocks, {
        hash: 'cos',
        timestamp: timeStamp(),      
        dataOfBlock: this.state.value,
        nounce: '',
        index: this.state.blocks.length
      }]
© www.soinside.com 2019 - 2024. All rights reserved.