首页 > 解决方案 > 为什么 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;

标签: javascriptreactjsethereumweb3

解决方案


很简单,你只需要在浏览器中启用以太坊,你可以这样做:只需添加“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);
      };

推荐阅读