简单整合react的合约(二)
创建webClient.js, 将(一)中 export 的代码复制到这个文件
import Web3 from 'web3'; let selectedAccount; export const init = () => { let provider = window.ethereum; if(typeof provider !== 'undefined'){ provider .request({method: 'eth_requestAccounts'}) .then(accounts =>{ selectedAccount = accounts[0]; console.log(`Selected Account is ${selectedAccount}$`); }).catch((err)=>{ console.log(err); }); // 监听metamask 账号改变 window.ethereum.on('accountsChanged', function(accounts){ selectedAccount = accounts[0]; console.log(`Selected Account is ${selectedAccount}$`); }); } const web3 = new Web3(provider); };
App.js 修改为
import logo from './logo.svg'; import './App.css'; //import './polyfill.js'; import Web3 from 'web3'; import React, {useEffect} from 'react'; import {init} from './Web3Client' function App() { //const providerUrl = process.env.PROVIDER_URL || 'http://localhost:7545'; useEffect(() => { init(); }, []); return <div className='App'></div> } export default App;
再运行,换个 账号可以看到console 输出账号