【发布时间】:2021-09-19 10:57:39
【问题描述】:
我正在开发一个按钮组件,用于处理将用户连接到他们的 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>
);
}
}
【问题讨论】:
标签: javascript ethereum web3 web3js metamask