[英]How to use variables from outside of a react component
I have an async
function outside of my react component which retrieves 2 token balances from 2 addresses.我的反应组件外部有一个
async
function ,它从 2 个地址检索 2 个令牌余额。 I want to render out the balances of the 2 addresses, in the commented out HTML lines.我想在注释掉的 HTML 行中渲染出 2 个地址的余额。 Specifically
linkBalance
and balance
.具体
linkBalance
和balance
。 The useContext
hook I think maybe I could solve my problem using context
but I'm not sure. useContext
钩子我想也许我可以使用context
解决我的问题,但我不确定。
import { ethers } from 'ethers'
const { ethereum } = window
const provider = new ethers.providers.Web3Provider(window.ethereum);
const linkAddress = '0xa36085F69e2889c224210F603D836748e7dC0088'
const linkABI = require('../constants/erc20.json')
const linkContract = new ethers.Contract(linkAddress, linkABI, provider);
(async() => {
const accounts = await ethereum.request({ method: 'eth_accounts' })
const account = accounts[0]
const balance = await provider.getBalance(account)
console.log(ethers.utils.formatUnits(balance, 18))
const linkBalance = await linkContract.balanceOf(contractAddress)
console.log(ethers.utils.formatUnits(linkBalance, 18))
})()
const Main = () => {
const { connectWallet, currentAccount } = useContext(PackPlayersContext)
return(
<>
<div>
{currentAccount && (<p>Current Address: {currentAccount}</p>)}
{!currentAccount && (
<button className="bg-blue-500 hover:bg-blue-700 text-white font-bold py-2 px-4 rounded" onClick={connectWallet}>Connect Wallet</button>
)}
<input className="shadow appearance-none border rounded w-half py-2 px-3 text-gray-700 leading-tight focus:outline-none focus:shadow-outline" id="username" type="text" placeholder="Price"/>
<button className="bg-blue-500 hover:bg-blue-700 text-white font-bold py-2 px-4 rounded mb-4 mt-4">Buy Pack</button>
{/*
<div>
<p>Current link balance of contract: {linkBalance}</p>
<p>Your KETH balance: {balance}</p>
</div>
*/}
</div>
</>
)
}
export default Main
I have returned victorious.我已经胜利归来。
I create a separate file to place my async function, and use it as a context provider, in that context provider I updated a state which holds my token balances.我创建了一个单独的文件来放置我的异步 function,并将其用作上下文提供程序,在该上下文提供程序中,我更新了一个包含我的代币余额的 state。 I then passed in as context to my html.
然后我将上下文作为上下文传递给我的 html。
Here is the context file这是上下文文件
import React, { useState, useEffect} from 'react'
import { contractAddress } from '../constants/constants'
import { ethers } from 'ethers'
const { ethereum } = window
export const BalancesContext = React.createContext()
const provider = new ethers.providers.Web3Provider(window.ethereum);
const linkAddress = '0xa36085F69e2889c224210F603D836748e7dC0088'
const linkABI = require('../constants/erc20.json')
const linkContract = new ethers.Contract(linkAddress, linkABI, provider);
export const BalancesProvider = ({ children }) => {
const[currentLinkBalance, setCurrentLinkBalance] = useState()
const[currentKethBalance, setCurrentKethBalance] = useState()
const getBalances = async () => {
const accounts = await ethereum.request({ method: 'eth_accounts' })
const account = accounts[0]
const balance = await provider.getBalance(account)
console.log(ethers.utils.formatUnits(balance, 18))
setCurrentKethBalance(ethers.utils.formatUnits(balance, 18))
const linkBalance = await linkContract.balanceOf(contractAddress)
console.log(ethers.utils.formatUnits(linkBalance, 18))
setCurrentLinkBalance(ethers.utils.formatUnits(linkBalance, 18))
}
useEffect(() => {
getBalances()
}, [])
return (
<BalancesContext.Provider value ={{ currentLinkBalance, currentKethBalance }}>
{children}
</BalancesContext.Provider>
)
}
And here is the new Main component这是新的主要组件
import { PackPlayersContext } from "../context/PackPlayersContext"
import React, { useContext, useState } from 'react'
import { BalancesContext } from "../context/BalancesContext"
const Main = () => {
const { connectWallet, currentAccount } = useContext(PackPlayersContext)
const { currentLinkBalance, currentKethBalance } = useContext(BalancesContext)
return(
<>
<div>
{currentAccount && (<p>Current Address: {currentAccount}</p>)}
{!currentAccount && (
<button className="bg-blue-500 hover:bg-blue-700 text-white font-bold py-2 px-4 rounded" onClick={connectWallet}>Connect Wallet</button>
)}
<input className="shadow appearance-none border rounded w-half py-2 px-3 text-gray-700 leading-tight focus:outline-none focus:shadow-outline" id="username" type="text" placeholder="Price"/>
<button className="bg-blue-500 hover:bg-blue-700 text-white font-bold py-2 px-4 rounded mb-4 mt-4">Buy Pack</button>
<div>
<p>Current link balance of contract: {currentLinkBalance}</p>
<p>Your KETH balance: {currentKethBalance}</p>
</div>
</div>
</>
)
}
export default Main
Thank you all for your help and suggestions.谢谢大家的帮助和建议。 Lastly, I'm new to react and js so I honestly have no idea if this was a stupid way to do it but it works correctly.
最后,我是 react 和 js 的新手,所以老实说,我不知道这是否是一种愚蠢的做法,但它可以正常工作。 But, I'm always open to learning best practices so please comment if anything is done wrong or stupidly.
但是,我总是乐于学习最佳实践,所以如果有任何错误或愚蠢的做法,请发表评论。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.