[英]Balance is not updated when user changes account
每次在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 });
})
}
我認為問題在於試圖改變 function 內部的平衡。 所以你並沒有真正改變你已經定義的余額值。 嘗試:
web3.eth.getBalance(acc,(err,bal)=> {
this.setState({ balance: bal })
})
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.