首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >反应:将事件监听纳入web3js承诺

反应:将事件监听纳入web3js承诺
EN

Ethereum用户
提问于 2018-03-15 04:15:55
回答 1查看 1.5K关注 0票数 2

我有以下反应成分:

代码语言:javascript
复制
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)的实体事件。我想听这个事件来提醒您成功的消息,但是我想不出如何将事件侦听合并到代码中。最好的办法是什么?

EN

回答 1

Ethereum用户

发布于 2018-04-27 06:52:33

https://web3js.readthedocs.io/en/1.0/web3-eth-contract.html#events-allevents

您可以在componentWillMount中这样做,例如:假设契约是已部署的契约的实例

代码语言:javascript
复制
    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

票数 1
EN
页面原文内容由Ethereum提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://ethereum.stackexchange.com/questions/42800

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档