Const无法定义反应

问题描述 投票:-1回答:1

我不能在反应中定义const。

启动Web浏览器后,我在console命令中键入accounts时出错。

>accounts
VM768:1 Uncaught ReferenceError: accounts is not defined
    at <anonymous>:1:1
(anonymous) @ VM768:1

我认为这是Web3错误,所以我在控制台命令中定义了accounts。但是我可以定义accounts

>const accounts = web3.eth.accounts[0]
<undefined

>accounts
<"0xeb827c448545--------1a7d5ced86ac3"

我想通过this.state.account显示地址。

你能给我任何建议吗?

import React, { Component } from 'react';
import Web3 from 'web3';
import './App.css';

class App extends Component {

  conponentWillmount() {
    this.loadBlockchainData()
  }

  async loadBlockchainData() {
    const web3 = new Web3(Web3.givenProvider || "http://localhost:7545")
    const network = await web3.eth.net.getNetworkType()
    console.log("network:", network)
    const accounts = await web3.eth.accounts[0]
    this.state({ account: accounts[0]}) 
    console.log("account:", accounts[0])
    // Fetch Account
  }

  constructor(props) {
    super(props)
    this.state = { account: ''}
  }

  render() {
    return (
      <div className="container">
        <h1>Hello world</h1>
        <p>Your account : {this.state.account} </p>
      </div>
    );
  }
}

export default App;
reactjs blockchain ethereum web3js
1个回答
1
投票

const accounts = await web3.eth.accounts[0]变量是loadBlockchainData方法的局部变量。无法从控制台命令行访问它,因为只能从那里访问全局变量。

如果需要在浏览器开发工具中调试accounts,可以在loadBlockchainData中设置断点。

© www.soinside.com 2019 - 2024. All rights reserved.