如何将值从 useState 传递到 web3 中的 balanceOf 函数
How Can I pass value from useState into balanceOf function in web3
我正在创建一个 DEFI dapp,我想使用 web3.eth.get accounts();
获取与元掩码关联的帐户
这是我在console.log ['0x32F36b36e78E89bdd6efa9e893ec2d87e4E2e3E9']时得到的,
我创建了 use State 来推动此帐户在 React 组件中用作道具,但是当我 console.log useState 的值时,我什么也得不到。
那么如果我要在 useState 中获取这个值,我该如何将它传递给 balanceOf 函数?
useState
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);
您应该在 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]);
我正在创建一个 DEFI dapp,我想使用 web3.eth.get accounts();
获取与元掩码关联的帐户这是我在console.log ['0x32F36b36e78E89bdd6efa9e893ec2d87e4E2e3E9']时得到的, 我创建了 use State 来推动此帐户在 React 组件中用作道具,但是当我 console.log useState 的值时,我什么也得不到。
那么如果我要在 useState 中获取这个值,我该如何将它传递给 balanceOf 函数?
useState
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);
您应该在 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]);