我试图在反应码“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到我的每块索引。
添加新对象时,可以使用length
作为新对象的索引
注:this.state.blocks.length
将在未来的指数,因为指数从0
启动
blocks: [...this.state.blocks, {
hash: 'cos',
timestamp: timeStamp(),
dataOfBlock: this.state.value,
nounce: '',
index: this.state.blocks.length
}]