【问题标题】:Use Web3 and Metamask in React在 React 中使用 Web3 和 Metamask
【发布时间】:2019-08-03 11:20:48
【问题描述】:

我正在尝试使用 React 创建我的第一个 dapp。 我不明白如何将 Web3.js 连接到 React 以及如何正确使用它。 你能展示如何正确地做到这一点吗? 也许我应该使用状态。 谢谢!

 import React, { Component } from 'react';
 import Web3 from 'web3';
 import ABI from './web3/ABI'

    class App extends Component {

        web3Connection = () => {
                let web3
                if (window.ethereum) {
                    web3 = new Web3(window.ethereum);
                    try {
                        window.ethereum.enable().then(function() {});
                    } catch (e) {}
                } else if (window.web3) {
                    web3 = new Web3(web3.currentProvider);
                } else {
                    alert('You have to install MetaMask !');
                }

                web3.eth.defaultAccount = web3.eth.accounts[0];


                const EthereumNoteContract = web3.eth.contract(ABI);

                const EthereumNote = EthereumNoteContract.at('address');

            }

        addMyNote = (_text) => {
                EthereumNote.addMyNote(_text, { value: 0 }, function(error, result) {
                    if (error) console.log(error);
                    else console.log(result)
                });
            }

        render() {

            return (
                <div>
                {this.web3Connection}
                <button onClick={this.addMyNote}>Send</button>
                </div>
            )
        }
    }

【问题讨论】:

    标签: reactjs web3 metamask


    【解决方案1】:

    假设您已安装 metamask chrome 扩展并已登录...还假设您已安装 web3 lib...

    给你:

    import React from 'react';
    import Web3 from 'web3'
    
    export default class App extends React.Component {
      state = {account: ''}
    
      async loadBlockChain() {
        const web3 = new Web3(Web3.givenProvider || 'http://localhost:8080')
        const network = await web3.eth.net.getNetworkType();
        console.log(network) // should give you main if you're connected to the main network via metamask...
        const accounts = await web3.eth.getAccounts()
        this.setState({account: accounts[0]})
      }
    
      componentDidMount() {
        this.loadBlockChain()
      }
      render() {
        return (
          <div>
            <p>Check out the the console....</p>
            <p>Your account: {this.state.account}</p>
          </div>
        );
      }
    }
    

    功能/挂钩:

    import React, { useState, useEffect } from "react";
    import Web3 from "web3";
    
    export default function App() {
      const [account, setAccount] = useState("");
    
      async function loadBlockChain() {
        const web3 = new Web3(Web3.givenProvider || "http://localhost:8080");
        const network = await web3.eth.net.getNetworkType();
        console.log(network); // should give you main if you're connected to the main network via metamask...
        const accounts = await web3.eth.getAccounts();
        setAccount(accounts[0]);
      }
    
      useEffect(() => loadBlockChain, []);
    
      return (
        <div>
          <p>Check out the the console....</p>
          <p>Your account: {account}</p>
        </div>
      );
    }
    

    【讨论】:

    • 如何在功能性反应组件中做到这一点?
    • @fuadnafiz98 - 见上文
    【解决方案2】:

    这是一个示例函数调用,您可以在 React 项目中使用 React 连接到 Metamask:

    export const connectWallet = async () => {
      if (window.ethereum) { //check if Metamask is installed
            try {
                const address = await window.ethereum.enable(); //connect Metamask
                const obj = {
                        connectedStatus: true,
                        status: "",
                        address: address
                    }
                    return obj;
                 
            } catch (error) {
                return {
                    connectedStatus: false,
                    status: "? Connect to Metamask using the button on the top right."
                }
            }
            
      } else {
            return {
                connectedStatus: false,
                status: "? You must install Metamask into your browser: https://metamask.io/download.html"
            }
          } 
    };
    

    在这个使用 React 创建 NFT 铸币机的教程中,他们有一个完整的例子来说明如何使用它,甚至使用 Metamask 签署交易:https://docs.alchemyapi.io/alchemy/tutorials/nft-minter#step-4-connect-metamask-to-your-ui

    【讨论】:

      猜你喜欢
      • 2018-07-21
      • 1970-01-01
      • 2019-07-05
      • 1970-01-01
      • 2019-05-24
      • 1970-01-01
      • 1970-01-01
      • 2021-07-30
      • 2021-08-23
      相关资源
      最近更新 更多