在 React 中使用 setState 更新对象(solidity 事件过滤器)
Posted
技术标签:
【中文标题】在 React 中使用 setState 更新对象(solidity 事件过滤器)【英文标题】:Updating an object with setState in React (solidity event filter) 【发布时间】:2020-07-23 13:54:41 【问题描述】:是否可以使用 setState 更新对象的属性?
类似:
this.state =
audit: name: "1", age: 1 ,
我可以使用以下命令将事件记录到控制台:-
myContract.once('MyEvent',
filter: myIndexedParam: [20,23], myOtherIndexedParam: '0x123456789...', // Using an array means OR: e.g. 20 or 23
fromBlock: 0
, function(error, event) console.log(event); );
我在控制台上创建的solidity ABI对象是
App.js:42
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
我需要 setState 所需的数据并在以后使用它,所以我像这样使用 .setState
showusingID(ids)
this.setState( loading: true )
this.state.instance.events.Artworkcreated(
filter: id: ids,
fromBlock: 0,
).on('data', function(event)
this.setState(...this.state.audit, name: 'someothername');
)
但它显示 .setState 不是一个函数。请帮帮我。
【问题讨论】:
上下文绑定问题?showusingID = ids =>
我尝试使用箭头函数进行绑定但得到 TypeError: Cannot read property 'audit' of undefined
【参考方案1】:
在on('data')
中使用箭头函数。
showusingID = ids =>
this.setState( loading: true )
this.state.instance.events.Artworkcreated(
filter: id: ids,
fromBlock: 0,
).on('data', event =>
this.setState(...this.state.audit, name: 'someothername');
)
【讨论】:
console.log 在哪里? 可能需要使用this.setState(prevState => ( ...prevState, name: 'someothername'))
。
我的错,无论如何感谢您的帮助和及时回复。您的解决方案对我帮助很大!以上是关于在 React 中使用 setState 更新对象(solidity 事件过滤器)的主要内容,如果未能解决你的问题,请参考以下文章
React拓展 - setState - 路由组件懒加载 - Hooks - Fragment - Context - PureComponent - 插槽 - 错误边界 - 组件通信方式总结(代码片