javascript - Web3 1.1.0 的问题
问题描述
我正在开发一个使用具有 Web3 作为依赖项的库的 React 应用程序。我以前可以使用以下代码获取当前的 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]);
}
});
Makbe 你还需要添加ethereum.enable();
. 希望这可以帮助。
推荐阅读
- jquery - 使用 window.innerHeight 的 Jquery 变量返回为未定义
- python - 使用 Pandas 在 DataFrame 中插入自定义系列作为新列
- apache - 烧瓶如何允许读/写文件访问
- python - python中的直方图图形问题
- java - 从tomcat WEB-INF中的文件创建文件对象
- flutter - 使用appbar后退按钮Flutter返回页面时Build()不会再次运行
- xcode - MTKView,为什么从 CAMetalLayer 到截图的颜色不同?
- tensorflow2.0 - 访问 TF2 keras 张量图的中间张量
- sql - 相互引用的列
- c# - 如何在c#中比较两个字典的元组值