Token.networks[networkId]在web3中返回undefined



我很难理解代码的一部分:

const networkId = await web3.eth.net.getId() // this line returns the id 
const PeePTokenData =  PeeP_Token.networks[networkId] // and this one? 

这会返回undefined,我不知道如何找到解决方案。在下方粘贴符合要求的代码

import React, { useState } from 'react'
import Web3 from 'web3';
import PeeP_Token from './build/PeeP_Token.json';
import Dummy_Token from './build/Dummy_Token.json';
import StakingDapp from './build/StakingDapp.json';

function App() {
const [isConnected, setIsConnected] = useState(false)
const [account, setAccount] = useState()
const [ethBalance, setEthBalance] = useState("")
const detectCurrentProvider = () => {
let provider;
if (window.ethereum) {
provider = window.ethereum
} else if (window.web3) {
provider = window.web3.currentProvider
} else {
window.alert(' Non-Ethereum browser detected, Ypu should consider trying Metamask')
}
return provider;
};
const onDisconnect = () => {
setIsConnected(false)
}
const onConnect = async() => {
try {
const currentProvider = detectCurrentProvider();
if (currentProvider) {
await currentProvider.request({method: 'eth_requestAccounts'})
const web3 = new Web3(currentProvider)
const userAccount = await web3.eth.getAccounts()
setAccount(userAccount[0])
setIsConnected(true)
const networkId = await web3.eth.net.getId()
const PeePTokenData =  PeeP_Token.networks[networkId]
console.log("🚀 ~ file: App.js ~ line 43 ~ onConnect ~ PeePTokenData", PeePTokenData)
if (PeePTokenData) {
const PeeP_token = new web3.eth.Contract(PeeP_Token.abi, PeePTokenData.address)
// some more code
}
}
} catch (error) {
console.log("🚀 ~ file: App.js ~ line 35 ~ onConnect ~ error", error)
}
}

return (
<div className="App">
<header className="App-header">
<h1>React App Auth</h1>
</header>
{!isConnected && (
<div className='app-wrapper'>

<button className='app-login' onClick={onConnect}>
Login
</button>
</div>
)}
{isConnected && (
<div className='app-wrapper'>
<h1>you are now connected</h1>
<div className="balance">

</div>
<button className='app-logout' onClick={onDisconnect}>
logout
</button>
</div>
)}
</div>
);
}
export default App;

我无法使用webpack导入json文件一次,所以我使用了fetch

const [contract,setContract]=useState(null)
useEffect(() => {
// make sure you are passing correct path
fetch("./build/PeeP_Token.json")
.then((data) => data.json())
.then((data) => setContract(data));

}, []);

相关内容

  • 没有找到相关文章

最新更新