以太坊DAPP[3]-×××-react特性与×××合约实例

×××实例

在之前的课程中,我们介绍了如何编译与部署合约。现在,我们假设已经把合约部署到了ropsten的网络之上。得到了地址。
现在,我们需要通过合约的ABI接口与地址来构建×××合约的实例。

新建文件:src/lottery.js:

1
2
3
4
5
6
7
import web3 from './web3';
const address = '0x94A261B507c4388f2ADcFfaA5685ffdF53ebcba5';

const abi = [{"constant":true,"inputs":[],"name":"manager","outputs":[{"name":"","type":"address"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":false,"inputs":[],"name":"getPlayers","outputs":[{"name":"","type":"address[]"}],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":false,"inputs":[],"name":"enetr","outputs":[],"payable":true,"stateMutability":"payable","type":"function"},{"constant":false,"inputs":[],"name":"pickwiner","outputs":[],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":true,"inputs":[{"name":"","type":"uint256"}],"name":"players","outputs":[{"name":"","type":"address"}],"payable":false,"stateMutability":"view","type":"function"},{"inputs":[],"payable":false,"stateMutability":"nonpayable","type":"constructor"}];


export default new web3.eth.Contract(abi,address);

src/App.js:
componentDidMount为react class的生命周期函数,其在reander之后执行。state是react中特殊的属性,其只是存在于class component中,用于存储属性。
当state中的状态变化之后,都会重新的执行reander函数,从而让页面展现出不同的效果。下面获取了管理者的地址并存储在了state状态变量中。在页面中显示了管理者的地址。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29

import React, { Component } from 'react';
import logo from './logo.svg';
import './App.css';
import web3 from './web3';
import lottery from './lottery';

class App extends Component {

  state = {
    manager:'',
  }

 async componentDidMount(){
     const manager = await lottery.methods.manager().call();
       this.setState({manager});
 }


 render() {
   return (
     <div>
       <h1>lottery管理者地址:</h1>
       <p>this is manager by  {this.state.manager}</p>
     </div>
   );
 }
}
export default App;

猜你喜欢

转载自blog.51cto.com/13784902/2330687