Web3js

如何在 reactjs 應用程序中正確配置 web3?

  • November 10, 2021

我目前正在建構一個使用 web3 庫連接到乙太坊的 React Dapp,但是當我嘗試進行任何 API 呼叫時,螢幕或瀏覽器控制台不會呈現任何內容。我還附上了項目原始碼。

我究竟做錯了什麼?

import React, { Component } from 'react';
import ReactDOM from 'react-dom';
import './index.css';
import Web3 from 'web3';

class Wallet extends Component {
   constructor(props) {
       super(props);
       this.accounts = this.props._accounts;
       this.account_len = this.props.length;
       this.defKeyName = this.props.defaultKeyName;
   }

   render() {
       return (
           <div className="container1">
               <h1> Wallet Data </h1>
               <p>{this.props._accounts} </p>
           </div>
       );
   }
}
class App extends Component {
   componentDidMount() {
       this.loadBlockchainData()
   }

   async loadBlockchainData() {
       var wallet = await this.state.web3.eth.accounts.wallet;
       this.setState({wallet: wallet});
   }

   async createAccount() {
       var account = await this.state.web3.eth.accounts
       this.setState({account: account[0]});
   }


   constructor(props) {
       super(props);
       this.createAccount = this.createAccount.bind(this)
       this.state = { 
           web3: new Web3(new Web3.providers.HttpProvider("HTTP://127.0.0.1:7545")),
           wallet: '',
       };
   }

   render() {
       return (
           <div className="container">
               <h1>Hello, World!</h1>
               <Wallet props={this.state.wallet}/>
               <button type="button" onClick={this.createAccount}>Create account
               </button>
           </div>
       );
   }
}

ReactDOM.render(<App />, document.getElementById("root"))

export default App;
import React, { Component } from 'react';
import './index.css';
import Web3 from 'web3';

class Wallet extends Component {
   render() {
       return (
           <div className="container1">
               <h1> Wallet Data </h1>
               <p>{this.props.account} </p>
           </div>
       );
   }
}

class App extends Component {
   async createAccount() {
       var account = await this.state.web3.eth.getAccounts();
       this.setState({account: account[0]});
   }


   constructor(props) {
       super(props);
       this.createAccount = this.createAccount.bind(this)
       this.state = { 
           web3: new Web3(new Web3.providers.HttpProvider("http://127.0.0.1:7545")),
           account: '',
       };
   }

   render() {
       return (
           <div className="container">
               <h1>Hello, World!</h1>
               <Wallet account={this.state.account}/>
               <button type="button" onClick={this.createAccount}>Create account
               </button>
           </div>
       );
   }
}

export default App;

當您點擊創建帳戶按鈕時,這將列印帳戶。如果您想查看完整的程式碼要點,請點擊此處

根據您目前的設置,在 componentDidMount 中呼叫它來獲取提供者:

componentDidMount(){
const loadProvider = async () => {
     let provider;
     if (window.ethereum) {
       provider = window.ethereum;

       try {
         await provider.request({ method: "eth_requestAccounts" });
       } catch {
         console.error("User denied account access");
       }
     } else if (window.web3) {
       provider = window.web3.currentProvider;
     } else if (!process.env.production) {
       provider = new Web3.providers.HttpProvider("http://localhost:7545");
     }
     // set the web3
     this.setState({
       web3: new Web3(provider),
       provider,
     });
   };

   loadProvider();
}

或者,您可以使用@metamask/detect-provider 檢測提供程序

componentDidMount(){
 const loadProvider = async () => {
   const provider = await detectEthereumProvider();
   if (provider) {
     provider.request({ method: "eth_requestAccounts" });
     this.setState({
       web3: new Web3(provider),
       provider,
     });

   } else {
     console.error("please install metamask");
   }}
    loadProvider();
}

獲取帳戶

async createAccount() {
   var account = await this.state.web3.eth.getAccounts()
   this.setState({account: account[0]});
}

引用自:https://ethereum.stackexchange.com/questions/112787