[英]How Can I pass value from useState into balanceOf function in web3
我正在创建一个 DEFI dapp,我想使用 web3.eth.get accounts() 获取与元掩码相关的帐户;
这就是我在 console.log ['0x32F36b36e78E89bdd6efa9e893ec2d87e4E2e3E9'] 时得到的,我创建了使用 State 来推送这个帐户以在 React 组件中作为道具使用,但是当我 console.log 的值 useState 我什么也没得到。
那么,如果我将在 useState 中获取此值,我该如何将其传递给 balanceOf function?
使用状态
const [userAccount, setUserAccount] = useState([]);
function 获取账户并获取该账户的余额
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);
您应该在useEffect
挂钩中获取帐户,因此当您的组件呈现时,您的组件的 state 将已经设置。
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]);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.