【Truffle系列第04篇】3分钟玩转一个简单的React DApp(下)

我们接着上一小节继续对reactDemo进行改造和Kovan网络部署。

最终效果如下

改造步骤

1. 终端通过如下命令行下载demo

liyc1215:reactDemo liyuechun$ truffle unbox react-box

2. 编译合约

命令行切换到reactDemo项目目录下,执行下面命令进行合约编译。

liyc1215:reactDemo liyuechun$ truffle compile

3. networks 内容替换

【Truffle系列第04篇】3分钟玩转一个简单的React DApp(下)

  • 1为测试网络MainNetId(networkId)
  • 3为测试网络RopstenId(networkId)
  • 42为测试网络KovanId(networkId)
  • address为部署到对应网络的合约地址。
  • transactionHash为合约部署时的交易hash

备注:下面合约部署完后,将合约地址和交易hash再到这个位置进行填充。

4. 合约部署

拷贝SimpleStorage.sol文件中的合约代码到https://remix.ethereum.org里面进行编译部署,我们把合约部署到ropsten网络。

【Truffle系列第04篇】3分钟玩转一个简单的React DApp(下)

5. 合约地址、交易hash存储

https://ropsten.etherscan.io/tx/0x41c85bf5b0c9b6e575e34cb047881f083bea66620ac00b7e421e0c74a0f1bd3e查看合约地址、交易hash。

【Truffle系列第04篇】3分钟玩转一个简单的React DApp(下)

6. 修改networks中的addresstransactionHash

"networks": {
    "3": {
      "events": {},
      "links": {},
      "address": "0x260182cd1111ac15c086b244ed6abc19aa4ab1e6",
      "transactionHash": "0x41c85bf5b0c9b6e575e34cb047881f083bea66620ac00b7e421e0c74a0f1bd3e"
    }
  }

7. 拷贝下面代码替换App.js代码

import React, { Component } from "react";
import SimpleStorageContract from "./contracts/SimpleStorage.json";
import getWeb3 from "./getWeb3";

// networkId
// Ropsten:3
// MainNet:1
// Kovan:42

import "./App.css";

class App extends Component {
  state = {
    value: "",
    storageValue: 0,
    web3: null,
    accounts: null,
    contract: null
  };

  componentDidMount = async () => {
    try {
      // Get network provider and web3 instance.
      const web3 = await getWeb3();

      // Use web3 to get the user's accounts.
      const accounts = await web3.eth.getAccounts();

      // Get the contract instance.
      const networkId = await web3.eth.net.getId();
      console.log("networkId:" + networkId);
      const deployedNetwork = SimpleStorageContract.networks[networkId];
      const instance = new web3.eth.Contract(
        SimpleStorageContract.abi,
        deployedNetwork && deployedNetwork.address,
      );

      // Set web3, accounts, and contract to the state, and then proceed with an
      // example of interacting with the contract's methods.
      this.setState({ web3, accounts, contract: instance });
    } catch (error) {
      // Catch any errors for any of the above operations.
      alert(
        `Failed to load web3, accounts, or contract. Check console for details.`,
      );
      console.error(error);
    }
  };

  handleChange = async (event) => {
    this.setState({value: event.target.value});
  };

  handleSubmit = async (event) => {
    event.preventDefault();
    // alert('A name was submitted: ' + this.state.value);
    console.log("------");
    var num = Number(this.state.value);
    console.log(num);
    const { accounts, contract } = this.state;

    // Stores a given value, 5 by default.
    await contract.methods.set(num).send({ from: accounts[0] });

    // Get the value from the contract to prove it worked.
    const response = await contract.methods.get().call();
    console.log("response:" + response);
    // Update state with the result.
    this.setState({ storageValue: response });

  };

  render() {
    if (!this.state.web3) {
      return <div>Loading Web3, accounts, and contract...</div>;
    }
    return (
      <div className="App">
        <h1>Good to Go!</h1>
        <p>Your Truffle Box is installed and ready.</p>
        <h2>Smart Contract Example</h2>
        <p>
          If your contracts compiled and migrated successfully, below will show
          a stored value of 5 (by default).
        </p>
        <p>
          Try changing the value stored on <strong>line 40</strong> of App.js.
        </p>
        <div>The stored value is: {this.state.storageValue}</div>

        <form onSubmit={this.handleSubmit}>
          <label>
            Modify:
            <input type="text" value={this.state.value} onChange={this.handleChange} />
          </label>
          <input type="submit" value="Submit" />
        </form>
      </div>
    );
  }
}

export default App;

8. 终端运行项目

【Truffle系列第04篇】3分钟玩转一个简单的React DApp(下)

该内容来自于互联网公开内容,非区块链原创内容,如若转载,请注明出处:https://htzkw.com/archives/24981

联系我们

aliyinhang@gmail.com