我正在使用Web3.js构建一个React.js应用程序,以便在浏览器中连接到MetaMask。
下面的函数恰好提供了所需的结果,它触发MetaMask打开并连接到钱包。
代码:
async componentDidMount() {
let adr = null;
try {
adr = await this.state.web3.eth.requestAccounts();
this.setState({
address: adr[0]
});
} catch (e) {
if (e.code === 4001) {
// EIP-1193 userRejectedRequest error
// If this happens, the user rejected the connection request.
console.log('Please connect to wallet.');
} else {
console.error(e.message);
}
}
}下面的函数具有相同的代码,但不是在装载React组件时自动调用,而是通过单击按钮来触发。不幸的是,结果如下所示:
TypeError: Cannot read properties of undefined (reading 'state')
at loginWithEth (WalletAuth.js:52)代码:
async loginWithEth() {
let adr = null;
try {
adr = await this.state.web3.eth.requestAccounts(); //that's line 52 where the errors is thrown
this.setState({
address: adr[0]
});
} catch (e) {
if (e.code === 4001) {
// EIP-1193 userRejectedRequest error
// If this happens, the user rejected the connection request.
console.log('Please connect to wallet.');
} else {
console.error(e.message);
}
}
}希望有人能帮助我!
谢谢!
发布于 2021-10-10 02:19:11
没有在类中绑定loginWithEth!
this.loginWithEth = this.loginWithEth.bind(this);谢谢你,朱奈德和帕瓜迪亚里奥。
https://stackoverflow.com/questions/69508838
复制相似问题