javascript - 为什么 web3.eth.getAccounts().then(console.log) 返回空数组?
问题描述
在我尝试之后我得到了一个空数组web3.eth.getAccounts().then(console.log);
并且也得到了一个警告,即./node_modules/web3-eth-accounts/src/scrypt.js Critical dependency: the request of a dependency is an expression
. 在这个项目中,我首先发出命令create-react-app lottery_react
,然后我在lottery_react
文件夹中所做的所有更改App.js
都只用一行进行修改web3.eth.getAccounts().then(console.log);
并创建web3.js
文件。我在这些文件中找不到什么问题。请帮忙!
这是我的 App.js
import React, {Component} from 'react';
import logo from './logo.svg';
import './App.css';
import web3 from './web3';
class App extends Component {
render(){
web3.eth.getAccounts().then(console.log);
return (
<div className="App">
<header className="App-header">
<img src={logo} className="App-logo" alt="logo" />
<p>
Edit <code>src/App.js</code> and save to reload.
</p>
<a
className="App-link"
href="https://reactjs.org"
target="_blank"
rel="noopener noreferrer"
>
Learn React
</a>
</header>
</div>
);
}
}
export default App;
这是我的 web3.js 文件
import Web3 from 'web3';
const web3 = new Web3(window.web3.currentProvider);
export default web3;
解决方案
很简单,你只需要在浏览器中启用以太坊,你可以这样做:只需添加“await window.ethereum.enable();”
const getData = async () => {
const web3 = new Web3(Web3.givenProvider);
const network = await web3.eth.net.getNetworkType();
await window.ethereum.enable();
const accounts = await web3.eth.getAccounts();
setAccount(accounts[0]);
console.log("TCL: getData -> network", network);
console.log("TCL: getData -> accounts", accounts);
};
推荐阅读
- pytorch - 如何从 bert 微调模型中获取嵌入?
- mysql - 如果组中存在所有值,则 SQL group_by 和 group_concat
- maxima - Plot2d 切入 3D 函数
- laravel-lighthouse - 如何编写查询以列出相关模型
- r - 如何在 R Markdown 中创建全宽图形
- cassandra - 我应该如何在 Cassandra 中设置复制因子以解决节点故障?
- javascript - 获取 HTML5 中视频元素的控件(洗涤器)元素
- r - 在 R 中操作矩阵的条目
- python - Locust 可以运行与 UI 交互的脚本吗?
- reactjs - 定时器组件在超时后继续运行