reactjs - 尝试通过 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();
错误:
App.js:16 Uncaught (in promise) TypeError: Cannot read properties of null (reading 'eth') at setUserAccount (App.js:16)
store.js:20 未捕获的错误:未知类型的操作 ${action.type
index.js:1 上述错误发生在组件:在StoreProvider (http://localhost:3000/static/js/main.chunk.js:847:3)
解决方案
看起来您导入 useWeb3 错误:
const web3 = useWeb3();
但是你像这样导出它:
export {useWeb3};
所以现在你必须这样称呼它:web3.useWeb3()
您是否在某处的教程中找到了此代码?很难跟...
推荐阅读
- ios - 缓存一个网页(Typeform),离线时在WKWebView中打开
- python - 为什么我的变量导入会导致代码冲突?
- java - Android 11 错误:应用程序因 java.lang.SecurityException 崩溃:uid xxxxx 无法显式添加类型为:package.name 的帐户
- node.js - 嵌套参考使用猫鼬和 Nodejs 填充
- load-balancing - 负载均衡器的负载均衡
- php - 419 会话在设置“SESSION_DOMAIN”环境值后过期
- apache-kafka - 是否建议在消费者读取 kstream 消息密钥或消息后更改它以存储内部状态
- r - 在 ggplot/ggplotly 中使用 facet_wrap 时如何防止 y 轴挤压标签?
- javascript - 如何获得具有预定义值的顶级父级的所需类别树
- c++ - Box2D SetAsBox 构造函数的区别