Web3js

ComponentDidMount 未檢測到 Metamask 更改帳戶

  • August 31, 2020

我對 Web3 和 Metamask 很陌生,想問一下我應該如何更改 React truffle box 的基本 componenDidMount 以便在我在 Metamask 上切換帳戶時它可以檢測和更改帳戶。

這是程式碼:

Class App extends Component {
   state = {
   web3: null,
   contract: undefined,
   account: null
   }
componentDidMount = async () => {
 try {
 // Get network provider and web3 instances.
 const web3 = await getWeb3();

 // Use web3 to get the user's accounts.
 const accounts = await web3.eth.getAccounts();
 // Get the contract instance.
 const networkId = await web3.eth.net.getId();
 const deployedNetwork = SupChain.networks[networkId];
 const instance = new web3.eth.Contract(SupChain.abi, deployedNetwork && 
 deployedNetwork.address);
 // Set web3, accounts, and contract to the state
 this.setState({ contract: instance, web3: web3, account: accounts[0] });
} catch (error) {
 // Catch any errors for any of the above operations.
    alert(`Failed to load web3, accounts, or contract. Check console for details.`,
 );
 console.error(error);
}
  };
}

我提前感謝任何願意花時間幫助我的人。

當使用者更改帳戶、註銷、更改網路時,Metamask 會觸發事件。開始閱讀官方文件,了解如何實現事件監聽器。

引用自:https://ethereum.stackexchange.com/questions/87058