为什么我的变量在 web3 的 reactjs 中未定义

why is my variable undefined in reactjs with web3

我正在尝试使用 reactJS 来显示带有 web3 的以太坊钱包的余额。 我的代码成功获得余额并将其输出到控制台,但是当我尝试将其分配为变量并将其显示在 html 中时,出现以下错误: 第 19:37 行:'etherval' 未定义 no-undef

脚本:

import React from 'react';
import Web3 from 'web3'

export default function balances() {

const web3 = new Web3(new Web3.providers.HttpProvider('https://****'));
web3.eth.getBalance("0x****", function(err1, balance) {
{
    console.log(web3.utils.fromWei(balance, "ether") + " ETH")
    const etherval = web3.utils.fromWei(balance, "ether");
  }
})

  return (
    <div className="details">
      <div className="container">
        <div className="row">
          <div className="col-md-12">
                      <h2>Balance: {etherval}</h2>

          </div>
        </div>
      </div>
    </div>
  );
}

我尝试用 let 初始化变量,但这会产生更多错误,我该如何解决?

在useEffect中获取balance并设置为state:

import { useEffect,useState } from "react";


const [balance, setBallance] = useState(null)

useEffect(() => {
    const loadBalance = async () => {
      // make sure web3 is properly
      const web3 = new Web3(new Web3.providers.HttpProvider('https://****'));
      const balance = await web3.eth.getBalance(addressHere)
      setBallance(web3.utils.fromWei(balance, "ether"))
    }

    loadBalance()
  }, [])
import React, {useState} from 'react';
import Web3 from 'web3'

export default function Balances() {

const [balance, setBalance] = useState(0)
const web3 = new Web3(new Web3.providers.HttpProvider('https://****'));
web3.eth.getBalance("0x****", function(err1, balance) {
{
    console.log(web3.utils.fromWei(balance, "ether") + " ETH")
    setBalance(web3.utils.fromWei(balance, "ether"));
  }
})

  return (
    <div className="details">
      <div className="container">
        <div className="row">
          <div className="col-md-12">
                      <h2>Balance: {balance}</h2>

          </div>
        </div>
      </div>
    </div>
  );
}

您可以使用 useState 挂钩并在获得值后分配该值。如果此版本未呈现正确的数量,您也可以使用 useEffect 挂钩