我有以下反应成分:
class Parent extends Component {
constructor(props) {
super(props)
this.state = {
id: this.props.id,
age: 0,
web3: null,
}
this.setAge= this.setAge.bind(this)
}
componentWillMount() {
getWeb3
.then(results => {
this.setState({
web3: results.web3
})
this.getData()
})
.catch(() => {
console.log('Error finding web3.')
})
}
getData(){
const contract = require('truffle-contract')
const book = contract(Book)
book.setProvider(this.state.web3.currentProvider)
var bookInstance
this.state.web3.eth.getAccounts((error, accounts) => {
book.deployed().then((instance) => {
bookInstance = instance
return bookInstance.ageOf.call(this.props.id, {from: accounts[0]})
}).then((result) => {
return this.setState({age: result})
})
})
}
setAge() {
const contract = require('truffle-contract')
const book = contract(Book)
book.setProvider(this.state.web3.currentProvider)
var bookInstance
this.state.web3.eth.getAccounts((error, accounts) => {
book.deployed().then((instance) => {
bookInstance = instance
return bookInstance.ageOf.call(this.props.id, {from: accounts[0]})
}).then((result) => {
return bookInstance.setAge(this.props.id, {from: accounts[0], value: result, gas: 1000000, gasPrice: this.state.web3.toWei(10, 'gwei')})
})
})
})
}
render() {
return (
<div>
<button onClick={this.setAge}>set age</button>
</div>
)
}
}
export default Parent 我有一个函数setAge(),它触发一个名为ageSet(uint256 id, uint256 age)的实体事件。我想听这个事件来提醒您成功的消息,但是我想不出如何将事件侦听合并到代码中。最好的办法是什么?
发布于 2018-04-27 06:52:33
https://web3js.readthedocs.io/en/1.0/web3-eth-contract.html#events-allevents
您可以在componentWillMount中这样做,例如:假设契约是已部署的契约的实例
contract.allEvents({
fromBlock: 'latest',
}, function (error, event) {
if (error)
alert("error while subscribing to event")
console.log(event)
}
})这将侦听来自最新块的事件。这意味着您不会忘记过去的事件,但也有一个api:
https://web3js.readthedocs.io/en/1.0/web3-eth-contract.html#getpastevents
https://ethereum.stackexchange.com/questions/42800
复制相似问题