每次尝试在 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 });
})
}
答案 0 :(得分:0)
我认为问题出在试图改变函数内部的平衡。因此,您实际上并没有改变已经定义的余额值。尝试:
web3.eth.getBalance(acc,(err,bal)=> {
this.setState({ balance: bal })
})