簡體   English   中英

如何在 React 組件中使用 getter 函數?

[英]How to use a getter function inside a React component?

我正在嘗試制作一個基本的 React 組件來從已部署的合同中檢索一個值。 在此示例中,我使用輸入框接收合約地址(這是 ERC20 代幣在 localhost 上的部署地址)並填充Balance組件的addr狀態變量。

單擊Get Balance按鈕時,應檢索合約的 max_supply 並使用該值更新balance狀態變量。

我能夠部署 ERC20 代幣合約。 但是,我無法從我的Balance組件中檢索s_maxSupply() getter 的值。 這甚至可能嗎? 如果沒有,任何替代方案將不勝感激。 先感謝您。

import { useState } from 'react';
import { ethers } from 'ethers';
import OilToken from '../artifacts/contracts/OilToken.sol/OilToken.json'


const Balance = () => {
    const [addr, setAddr] = useState('---');
    const [balance, setBalance] = useState(0);
    let _balance = 0;

    async function getBalanceFromContract() {

        if (typeof window.ethereum !== 'undefined') {
            const [account] = await window.ethereum.request({ method: 'eth_requestAccounts' })
            const provider = new ethers.providers.Web3Provider(window.ethereum);
            const contract = new ethers.Contract(addr, OilToken.abi, provider)
            _balance = contract.s_maxSupply();
        }
    }

    function _setBalance() {
        getBalanceFromContract();
        setBalance(_balance);
    }

    return (
        <div>
            <br />
            <input onChange={e => setAddr(e.target.value)} placeholder="Enter account address" value={addr} />
            <button onClick={_setBalance}>Get Balance</button>
            <br />
            <div>The Max Supply of tokens is: {balance}</div>
        </div>
    );
}

export default Balance

為了完整起見,下面提供了 ERC20 代幣。

pragma solidity ^0.8.6;

import "@openzeppelin/contracts/token/ERC20/extensions/ERC20Votes.sol";

contract OilToken is ERC20Votes {
    uint256 public s_maxSupply = 1000 * 10**18;

    mapping 

    constructor() ERC20("OilToken", "OIL") ERC20Permit("GovernanceToken") {
        _mint(msg.sender, s_maxSupply);
    }


 
    function _afterTokenTransfer(
        address from,
        address to,
        uint256 amount
    ) internal override(ERC20Votes) {
        super._afterTokenTransfer(from, to, amount);
    }

    function _mint(address to, uint256 amount) internal override(ERC20Votes) {
        super._mint(to, amount);
    }

    function _burn(address account, uint256 amount)
        internal
        override(ERC20Votes)
    {
        super._burn(account, amount);
    }
}

contract.s_maxSupply() 將返回承諾,所以你需要這樣寫

_balance = await contract.s_maxSupply();

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM