1. 程式人生 > >以太坊DAPP[3]-×××-react特性與×××合約例項

以太坊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;