【问题标题】:Balance is not updated when user changes account用户更改帐户时余额不更新
【发布时间】:2020-09-08 22:39:12
【问题描述】:

每次在metamask中更改帐户时,我都会尝试更新地址和余额,但是只有帐户在更改并且余额没有更新。

async componentDidMount(){
    let accs = await web3.eth.getAccounts();
    let balance = await web3.eth.getBalance(accs[0]);
    let balanceth = await web3.utils.fromWei(balance,'ether');
    console.log(balanceth+" ether");
    this.setState({ balanceth });
    this.setState({ account:accs[0] });
      window.ethereum.on('accountsChanged',  (accounts) => {

          console.log(accounts[0]);
          this.setState({ account:accounts[0] });
          let acc = this.state.account;
          // Time to reload your interface with accounts[0]!
          web3.eth.getBalance(acc,(err,bal)=> {balance = bal})
          console.log(balance)
          web3.utils.fromWei(balance,'ether',(err,bal)=>{balanceth = bal});
          console.log(acc,balanceth);
          this.setState({ balanceth:balanceth });
  })
  }

【问题讨论】:

  • 你能显示你的输入字段的html吗?

标签: reactjs web3 metamask


【解决方案1】:

我认为问题在于试图改变函数内部的平衡。所以你并没有真正改变你已经定义的余额值。试试:

web3.eth.getBalance(acc,(err,bal)=> {
    this.setState({ balance: bal })
})

【讨论】:

    猜你喜欢
    • 2014-11-29
    • 2020-11-07
    • 2018-04-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-08-31
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多