首页 > 解决方案 > 尝试通过 web3.js 将 Metamask 钱包连接到我的反应应用程序

问题描述

我正在尝试将 metamask 钱包连接到我的 react-app。但在此过程中,我遇到了一些错误,如下所述,请帮助。

获取Web3.js

import Web3 from 'web3';
import {useEffect, useState} from 'react';

// Wallet connect code




const useWeb3 = () => {
    const [web3,setweb3] = useState(null);

    useEffect(() => {
        var instance;
        if(window.ethereum) {
            try{
                instance = new Web3(window.ethereum);
            }catch(error){
                console.error(error);
            };
        }else if (window.web3) {
            instance =  new Web3(window.web3);
        }else{
            const provider = new Web3.provider.HttpProvider('http://127.0.0.1:8545')
            instance = new Web3(provider);
        }setweb3(instance);
     
    },[]);

    return web3;

};

export {useWeb3};

store.js

import React, {useReducer, useContext, createContext} from 'react';

const StoreContext = createContext();

const initialState = {
    message: '',
    address: null,
    balance: 0
};

const reducer = (state, action) => {
    switch(action.type){
        case "NEW-ADDRESS":
            return {
                ...state,
                address: action.newAddress,
                message: action.message
            }
        default:
            throw new Error('Unknown type of action ${action.type');
    }
};

export const StoreProvider = ({children}) => {
    const [state, dispatch] = useReducer(reducer, initialState);

    return (
        <StoreContext.Provider value = {{state, dispatch}}>
            {children}
        </StoreContext.Provider>
        );
};

export const useStore = () => useContext(StoreContext);

storeApi.js

import {useStore} from './store'

const useStoreApi = () => {
    const {state, dispatch} = useStore();

    return {
        address: state.address,
        balance: state.balance,
        message: state.message,
        setBalance: (newBalance) => {
            dispatch({
                type: "SET-BALANCE",
                newBalance
            });
        },
        setAddress: newAddress => {
            dispatch({
                type: "New-Address",
                newAddress,
                message: "New account added successfully!"
            });
        }
    };
};

export {useStoreApi};

应用程序.js

import { useStoreApi } from './storeApi';
import { useWeb3 } from './getWeb3';
import logo from './logo.svg';
import './App.css';
import {Button} from '@material-ui/core';

function App() {
  const {address,balance,message, setBalance,setAddress} = useStoreApi();
  const web3 = useWeb3();

  const setUserAccount = async (e) => {
    console.log("rhis add");

    if(window.ethereum) {
      await window.ethereum.enable();
      web3.eth.getAccounts().then(accounts => {
        setAddress(accounts[0]);
        console.log("rhis add");
      });

    }


  };
  setUserAccount();
  return (
    <div className="App">
      <header className="App-header">
        <img src={logo} className="App-logo" alt="logo" />
        <p>
           <code>src/App.js</code> 
        </p>
        {
          address ? (
            <>
            <p> Your add: {address}</p></>
          ): "s"
         }
        {/* <Button variant="outlined" color="primary" onClick={() => setUserAccount()}>Conn</Button> */}
        {/* <form action="http://localhost:3000/">
          <button type="submit" onClick={() => setUserAccount()}>Submit</button>
        </form> */}


      </header>
    </div>
  );
}

export default App;

index.js

import React from 'react';
import ReactDOM from 'react-dom';
import './index.css';
import App from './App';
import reportWebVitals from './reportWebVitals';
import {StoreProvider} from './store';

ReactDOM.render(
  <React.StrictMode>
    <StoreProvider>
      <App />
    </StoreProvider>
  </React.StrictMode>,
  document.getElementById('root')
);


reportWebVitals();

错误:

  1. App.js:16 Uncaught (in promise) TypeError: Cannot read properties of null (reading 'eth') at setUserAccount (App.js:16)

  2. store.js:20 未捕获的错误:未知类型的操作 ${action.type

  3. index.js:1 上述错误发生在组件:在StoreProvider (http://localhost:3000/static/js/main.chunk.js:847:3)

标签: reactjsblockchainethereummetamask

解决方案


看起来您导入 useWeb3 错误:

const web3 = useWeb3();

但是你像这样导出它:

export {useWeb3};

所以现在你必须这样称呼它:web3.useWeb3()

您是否在某处的教程中找到了此代码?很难跟...


推荐阅读