我正在开发一个 React 应用程序,它使用一个以 Web3 作为依赖项的库。我以前能够使用以下代码获取当前的 Metamask 地址:
const injectedWeb3 = window.web3 || undefined;
this.state = {
web3: injectedWeb3
};
getAccount() {
const { web3 } = this.state;
if (web3.eth.accounts[0]) return web3.eth.accounts[0];
throw new Error('Your MetaMask is locked. Unlock it to continue.');
}
然后我将该库更新到最新版本,将其对 Web3 的依赖性更改为 Web3 1.0。现在,当我运行完全相同的代码时,出现以下错误:
Error: Invalid JSON RPC response: undefined
TypeError: e is not a function[Learn More]
关于可能发生的事情有什么想法吗?
最佳答案
我用这段代码解决了这个问题:
web3.eth.getAccounts(function (err, accounts) {
if (err != null) {
console.log(err)
}
else if (accounts.length === 0) {
console.log('MetaMask is locked');
}
else {
console.log('MetaMask is unlocked');
console.log(accounts[0]);
}
});
也许您还需要添加 ethereum.enable();
。
关于javascript - Web3 1.1.0 的问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55251544/