【问题标题】:How to properly update and retrieve account info with Metamask如何使用 Metamask 正确更新和检索帐户信息
【发布时间】:2021-09-19 10:57:39
【问题描述】:

我正在开发一个按钮组件,用于处理将用户连接到他们的 Metamask 钱包。这个想法是,如果用户的钱包尚未连接,那么按钮将显示“连接钱包”,一旦他们点击按钮并连接他们的钱包,按钮的文本将会改变,而是显示他们的帐户地址“0x323 ...”。

到目前为止,我唯一遇到的问题是更改帐户变量的状态并尝试从中检索地址。到目前为止,我所能做的就是登录 Metamask,但是一旦连接,地址就不会显示,因为它没有发现帐户变量的状态发生了变化。我在尝试更新帐户状态时尝试了不同的变体,但似乎没有任何效果。有什么我应该更改或包含在我的代码中的吗?


let ethereum = window.ethereum;
let accounts = [];

// Renders a Button to handle the Metamask Connection
class WalletConnector extends React.Component {

  constructor(props){
    super(props);
    this.state = {
      // set state of account to empty if not connected to a wallet
      accounts: ''
    }
  }

  handleClick(){
    try{
      // prompts to connect to metamask
      ethereum.request({ method: 'eth_requestAccounts' });

      // * this did not work * 
      //this.setState({accounts: ethereum.request({ method: 'eth_requestAccounts' })});
      
    }
    catch(error){
      // if user cancels metamask request 
      if (error.code === 4001){
        console.log('Metamask Connection Cancelled');
      }
      else {
        // if unable to requst account prompt to install metamask
        alert('Install Metamask to Connect');
      }
    }
  }

  render(){
    return(
      <div>
        <button onClick={this.handleClick}> 

          {/* if account is connected display address else ask to connect */}
          {this.state.accounts === '' ? 'Connect Wallet' : this.state.accounts} 

        </button>
      </div>
    );
  }

}

【问题讨论】:

    标签: javascript ethereum web3 web3js metamask


    【解决方案1】:

    您需要使用异步/等待。 ethereum.request 会返回一个承诺。

    async function handleClick() {
      try {
        // prompts to connect to metamask
        await ethereum.request({ method: "eth_requestAccounts" });
    
        this.setState({
          accounts: await ethereum.request({ method: "eth_requestAccounts" }),
        });
      } catch (error) {
        // if user cancels metamask request
        if (error.code === 4001) {
          console.log("Metamask Connection Cancelled");
        } else {
          // if unable to requst account prompt to install metamask
          alert("Install Metamask to Connect");
        }
      }
    }
    

    【讨论】:

      猜你喜欢
      • 2019-06-04
      • 2017-08-12
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-11-27
      • 2021-02-01
      • 2021-08-24
      • 2021-08-23
      相关资源
      最近更新 更多