[英]next.js - Getting error while building: Generating static pages (0/5)TypeError: Cannot read properties of undefined
[英]While running my next.js app that is using solidity smart contracts, I am getting "Cannot read properties of undefined" error
我正在运行我的 next.js 应用程序并尝试获取用户我收到“无法读取未定义的属性”错误
下面是我使用的代码
import Ewitter from './Ewitter.json';
import ethers from 'ethers';
import { useState, useEffect } from 'react';
const ContractABI = Ewitter.abi;
const ContractAddress = '0x5FbDB2315678afecb367f032d93F642f64180aa3';
const Ethereum = typeof window !== 'undefined' && (window as any).ethereum;
const getEwitterContract = () => {
const provider = new ethers.providers.Web3Provider(Ethereum);
const signer = provider.getSigner();
const EwitterContract = new ethers.Contract(
ContractAddress,
ContractABI,
signer
);
return EwitterContract;
};
const useEwitter = () => {
// const Ewitter = getEwitterContract();
const [currentAccount, setCurrentAccount] = useState<string>('');
const [currentUser, setCurrentUser] = useState<string>('');
const connect = async () => {
try {
if (!Ethereum) {
alert('Please install MetaMask');
return;
}
const accounts = await Ethereum.request({
method: 'eth_requestAccounts',
});
if (accounts.length === 0) {
alert('Please unlock MetaMask');
return;
}
const account = accounts[0];
console.log('connected to account: ', account);
setCurrentAccount(account);
} catch (errors) {
console.log(errors);
}
};
useEffect(() => {
if(!Ethereum){
console.log("No ethereum wallet found, please install metamask")
return ;
}
connect();
}, []);
useEffect(() =>{
if(currentAccount){
getUser();
}
}, [currentAccount])
const getUser = async ()=>{
const contract = getEwitterContract();
const user = await contract.getUser(currentAccount);
const {avatar, bio, name, username, wallet} = user;
console.log(user);
return user;
}
return { connect, account: currentAccount };
};
export default useEwitter;
# Update1我已将import ethers from 'ethers'
更改为import {ethers} from 'ethers'
现在我遇到了这个错误
如果无法正确理解或者如果您想查看整个代码库,那么这是github 存储库的链接
https://github.com/ChiragDogra/ewitter/blob/userIssue/dapp/hooks/useEwitter.ts
信不信由你,我刚刚遇到了这个问题。
问题是您如何导入ethers
。 应该
import { ethers } from "ethers";
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.