我试图更新存储在数组中的对象。但是获取TypeError:prevState.blockHash是不可迭代的。
这是我的构造函数

constructor(props) {
  super(props)

  this.state = {
    dir:"",
    account: '',
    name: [],
    fido: [{
      logIndex: [],
      transactionIndex: [],
      transactionHash: [],
      blockHash: []
    }],
    loading: true
  }


我以这种方式设置状态-

showusingBot= () => {
  this.setState(this.initialState)
  this.state.instance.events.Artworkcreated({
    filter: { purchased: false},
    fromBlock: 0
  }).on('data', event => {
    this.setState(prevState =>({
      fido:[...prevState.fido.map({blockHash: [
        ...prevState.blockHash,
        event.blockHash
      ]} )]}));
    })
  }


我在控制台上的ABI响应如下。

{logIndex: 0, transactionIndex: 0, transactionHash: "0x94f6d8671988ceb8ef1da862257637a198f4afefc3aef6cf3eb992dfcafb0eb1", blockHash: "0xd26937f8535a335663c9af57335f7cc783aba0e9e376408cbb92c1b3f1b28166", blockNumber: 20, …}
logIndex: 0
transactionIndex: 0
transactionHash: "0x94f6d8671988ceb8ef1da862257637a198f4afefc3aef6cf3eb992dfcafb0eb1"
blockHash: "0xd26937f8535a335663c9af57335f7cc783aba0e9e376408cbb92c1b3f1b28166"
blockNumber: 20
address: "0x20B40e09b75a21E0B857F695dE5De92a5A5b5AD0"
type: "mined"
id: "log_0d967aac"
returnValues: Result
0: "1"
1: "bhavin"
2: "masterpiece"
3: "1000000000000000000"
4: "100"
5: "200"
6: "blah blah blah!!"
7: "0x04f78093E2a1C07BF6c4527Aaa00807d3132A1Df"
8: false
id: "1"
Artistname: "bhavin"
Artname: "masterpiece"
price: "1000000000000000000"
width: "100"
height: "200"
Description: "blah blah blah!!"
owner: "0x04f78093E2a1C07BF6c4527Aaa00807d3132A1Df"
purchased: false
__proto__: Object
event: "Artworkcreated"
signature: "0xf912339172a3b7eda9cb10ecdef181d10a74fc4411fe5d7e62f550ef3698d845"
raw: {data: "0x000000000000000000000000000000000000000000000000…16820626c6168212100000000000000000000000000000000", topics: Array(4)}
__proto__: Object


我需要将一个字符串推入数组blockHash中。

最佳答案

您的整个fido地图回调不正确,应该使用一个函数,您正在传递一个对象。

this.setState(prevState =>({
  fido:[...prevState.fido.map({blockHash: [
    ...prevState.blockHash,
    event.blockHash
  ]} )]}));
})


正确的语法是map((current, index, originalArray) => {...})

但我认为您不需要映射任何东西,我想您只需要散布先前状态的fido数组并添加新元素

this.setState(prevState =>({
  fido:[...prevState.fido, event.blockHash]
}));


编辑1

正如您所说,由于fido是静态的,因此建议您将其属性存储在一个对象中,就像您当前将其作为数组中的元素一样。

this.state = {
  dir:"",
  account: '',
  name: [],
  fido: {
    logIndex: [],
    transactionIndex: [],
    transactionHash: [],
    blockHash: []
  },
  loading: true
}


现在,当更新fido状态时,以新元素散布在先前状态和blockHash数组中

this.setState(prevState =>({
  fido: {
    ...prevState.fido,
    blockHash: [...prevState.fido.blockHash, event.blockHash]
  },
}));


OFC,如果您希望/需要保持原样,则需要正确访问元素

this.setState(prevState =>({
  fido: [{
    ...prevState.fido[0],
    blockHash: [...prevState.fido[0].blockHash, event.blockHash]
  }],
}));

09-08 04:13