类型错误:无法读取未定义的属性(读取"合约")- 下一页.js web3.0



我正在尝试使用next.js创建一个小型的web3.0应用程序。我已经在rinkeby测试网络上部署了我的合同,我能够使用Remix检查功能,工作正常。我也在react上做过类似的项目,他们的工作也很出色。但当我尝试连接时,我目前面临以下问题(也许这与next.js或HttpProvider的服务器端渲染有关,我不确定(:

TypeError: Cannot read properties of undefined (reading 'Contract')
3 | import address from './build/campaignHubAddress.json';
4 | 
> 5 | const instance = new web3.eth.Contract(contract.abi, address.campaignHubAddress);
|                     ^
6 | export default instance;

web3.js

import Web3 from 'web3';
let web3;
if (typeof window !== 'undefined' && typeof window.ethereum !== 'undefined') {
window.ethereum.request({ method: "eth_requestAccounts" });
web3 = new Web3(window.ethereum);
} else {
const provider = new Web3.providers.HttpProvider(
'https://rinkeby.infura.io/v3/3ed112ee6c4d42a09e485ddb5eec5fa2'
);
web3 = new Web3(provider);
}
export default web3;

instance.js

import web3 from 'web3';
import contract from './build/CampaignHub.json';
import address from './build/campaignHubAddress.json';
const instance = new web3.eth.Contract(contract.abi, address.campaignHubAddress);
export default instance;

index.js

import React from 'react';
import web3 from '../web3';
import instance from '../instance';
class Index extends React.Component{
static async getInitialProps(){
const campaigns = await instance.methods.getCampaigns().call();
return { campaigns };
}
render() {
return (
<>
<p>Hello, this is the test page for now.</p>
<p>Web3 version: {web3.version}</p>
<p>List of all the running campaigns: {this.props.campaigns} </p>
</>
);
}
}
export default Index; 

这看起来很基本,但我已经坚持了一段时间了。

您已经在web3.js中创建了web3的实例您可以直接使用它而不使用";新的";

import web3 from 'web3';
import contract from './build/CampaignHub.json';
import address from './build/campaignHubAddress.json';
const instance = web3.eth.Contract(contract.abi, address.campaignHubAddress);
export default instance;

我费了很大的劲才发现错误在instance.js中。在导入import web3 from 'web3';时,我本应执行import web3 from './web3';

相关内容

  • 没有找到相关文章

最新更新