【问题标题】:How Can I pass value from useState into balanceOf function in web3如何将值从 useState 传递到 web3 中的 balanceOf 函数
【发布时间】:2022-01-04 10:12:14
【问题描述】:

我正在创建一个 DEFI dapp,我想使用 web3.eth.get accounts() 获取与元掩码关联的帐户;

这是我在 console.log ['0x32F36b36e78E89bdd6efa9e893ec2d87e4E2e3E9'] 时得到的, 我创建了 use State 来推送此帐户以在 React 组件中用作道具,但是当我 console.log 时 useState 的值我什么也没得到。

如果我要在 useState 中获取这个值,我该如何将它传递给 balanceOf 函数呢?

使用状态

const [userAccount, setUserAccount] = useState([]);

获取账户和获取该账户余额的功能

const blockchainDataLoad = async () => {

const web3 = window.web3;
console.log(userAccount);
// get the Accounts
const accounts = await web3.eth.getAccounts();
setUserAccount(accounts[0]);




// get the Network Id of The contracts
const networkId = await web3.eth.net.getId();

// ******************************** Dai Token EuroToken ************************* //

// Get the deployed contract object using the network ID
const daiTokenData = DaiToken.networks[networkId];

if(daiTokenData) {

  // Create a instance of the contract
  const daiToken = new web3.eth.Contract(DaiToken.abi, daiTokenData.address);
  setDTokens(daiToken);

  // get the balance from the investor account
  **let daiTokenBalance = await daiToken.methods.balanceOf(userAccount).call();**
  setDTokenBalance(daiTokenBalance.toString());
  console.log(daiTokenBalance);

【问题讨论】:

    标签: javascript reactjs ethereum solidity web3


    【解决方案1】:

    你应该在useEffect钩子中获取账户,所以当你的组件渲染时,你的组件的状态就已经设置好了。

    useEffect(() => {
        const getAccount = async () => {
          const accounts = await web3.eth.getAccounts();
          setAccount(accounts[0]);
        };
        // call getAccount() if web3 is defined otherwise you app will break
        web3 && getAccount();
      }, [web3]);
    

    【讨论】:

      猜你喜欢
      • 2023-04-02
      • 2021-12-02
      • 2018-12-17
      • 1970-01-01
      • 2019-12-30
      • 1970-01-01
      • 2020-02-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多