如何使用 Metamask 正确更新和检索帐户信息

问题描述

我正在开发一个按钮组件,用于将用户连接到他们的 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>
    );
  }

}

解决方法

你需要使用异步/等待。 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"); } } } 会返回一个 promise。

tf.keras.layers.TimeDistributed

相关问答

Selenium Web驱动程序和Java。元素在(x,y)点处不可单击。其...
Python-如何使用点“。” 访问字典成员?
Java 字符串是不可变的。到底是什么意思?
Java中的“ final”关键字如何工作?(我仍然可以修改对象。...
“loop:”在Java代码中。这是什么,为什么要编译?
java.lang.ClassNotFoundException:sun.jdbc.odbc.JdbcOdbc...