[區塊鏈] 利用Truffle框架建構一個簡單的以太坊應用程式 — Part 2. Truffle box — react

Chiwen Lai
6 min readApr 2, 2018

--

繼上一篇Part 1. 前置作業,將環境設定好之後,我們接下來將利用Truffle框架來建構我們的應用程式。

Part 2: Truffle box — react

▼先利用truffle box的框架「react」來配置我們的餐廳投票專案。

$ mkdir RestaurantsRating
$ cd RestaurantsRating
$ truffle unbox react

▼truffle unbox需要一段時間,專案配置完畢之後,檔案結構如下,node_modules裡的相依套件也都安裝好囉!

▼點選/src/App.js查看一下檔案內容。在App內設有一變數storageValue,預設值為0,程式一開始啟動成功的話,就會將storageValue設定為5,所以如果我們在頁面看到值為5的話,就表示合約執行成功囉!

// Get accounts.
this.state.web3.eth.getAccounts((error, accounts) => {
simpleStorage.deployed().then((instance) => {
simpleStorageInstance = instance
// Stores a given value, 5 by default.
return simpleStorageInstance.set(5, {from: accounts[0]})
}).then((result) => {
// Get the value from the contract to prove it worked.
return simpleStorageInstance.get.call(accounts[0])
}).then((result) => {
// Update state with the result.
return this.setState({ storageValue: result.c[0] })
})
})

▼接下來設定truffle.js,我們使用testrpc做測試,還記得在Part 1中testrpc的「Listening on localhost: 8545」,因此將port設定為8545。

module.exports = {
networks:{
development:{
host:"localhost",
port:8545,
network_id:'*'
}
}
};

設定完畢,可以開始我們的測試旅程。

▼開啟終端機畫面,將目錄切換到我們的RestaurantsRating。將合約部署到我們的testrpc上。
- truffle compile
- truffle migrate

$ cd RestaurantsRating
$ truffle compile
Compiling ./contracts/Migrations.sol...
Compiling ./contracts/SimpleStorage.sol...
Writing artifacts to ./build/contracts
$ truffle migrate
Using network 'development'.
Running migration: 1_initial_migration.js
Deploying Migrations...
... 0xd375750ae7bb2afda9646f6cd862cba8c9d4024adb7e8dcd5f0838377051a3c2
Migrations: 0x6aaa366574c1ebc1633e318583d631a9d0dafd97
Saving successful migration to network...
... 0xeeceb4ee2d581de23c6a3c303993681703e69b80de8c91cea4e9638ac92f18a0
Saving artifacts...
Running migration: 2_deploy_contracts.js
Deploying SimpleStorage...
... 0x581e0ef747650c1032a5b7460f3ce6e27ca11e0201938ef00a3a43fe27dc4ea3
SimpleStorage: 0xd56ba4bbf85b81090fbba0d9b612217a0e41044c
Saving successful migration to network...
... 0x9489c6bc48e4a033ddc165d82a4502b10c7035afe80c77b73719e8d8185ae56f
Saving artifacts...
$

▼再新增一個終端機頁面,啟動我們RestaurantsRating專案

$ cd RestaurantsRating
$ npm start

▼網頁會自動導到http://localhost:3000,一開始的時候顯示「The stored value is : 0」,MetaMask會自動跳出有交易待確認的對話框,因為網頁設定一開始就呼叫合約內的function:return simpleStorageInstance.set(5,{from: accounts[0]}) 。按下SUBMIT。

▼發現了嗎?The stored value is: 5. 修改成功!

--

--