webpack 令牌.networks[networkId]返回web3中未定义的值

kr98yfug  于 2022-11-13  发布在  Webpack
关注(0)|答案(1)|浏览(124)

我无法理解部分代码:

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;
lndjwyie

lndjwyie1#

我无法用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));
  
}, []);

相关问题