【发布时间】:2022-01-03 04:08:55
【问题描述】:
您好,我想知道是否有人遇到以下问题(未处理的拒绝(TypeError):info.contract.methods 未定义): enter image description here
这里是设置信息的地方 常量初始信息 = { 连接:假, 状态:空, 帐户:空, 合同:空, }; const intialDropState = { 加载:假, 列表:[], }; console.log(合约);
const DropList = () => {
const [info, setInfo] = useState(intialInfo);
const [drops,setDrops] = useState(intialDropState);
**我的智能合约通过执行以下操作调用 getDrops:
//Get the NFT drop objects list
function getDrops() public view returns(Drop[] memory) {
return drops;
}
**
这是有问题的代码部分
const getDrops = async() => {
setDrops(prevState => ({
...prevState,
loading: true,
}));
info.contract.methods
.getDrops()
.call()
.then((res) => {
console.log(res);
setDrops({
loading: false,
list: res,
});
})
.catch((err) => {
console.log(err);
setDrops(intialDropState);
});
};
这是代码
我在以下照片中拍摄了我所有代码的照片: enter image description here
import contract from "../contract/contract.json";
import Web3 from "web3";
import {useState, useEffect} from "react";
const intialInfo = {
connected: false,
status: null,
account: null,
contract: null,
};
const intialDropState = {
loading: false,
list:[],
};
console.log(contract);
const DropList = () => {
const [info, setInfo] = useState(intialInfo);
const [drops,setDrops] = useState(intialDropState);
// connecting to metamask and inital state of web dapp
const init = async() => {
//Connect to blockchain to metamask if there is a metamask
if(window.ethereum.isMetaMask){
const accounts = await window.ethereum.request({
method: "eth_requestAccounts",
});
const networkId = await window.ethereum.request({
method: "net_version",
});
//network == 4 for testnet for ETH use networkId == 1
if(networkId === 4){
let web3 = new Web3(window.ethereum);
setInfo({
...intialInfo,
connected: true,
account: accounts[0],
contract: new web3.ethereum.Contract(contract.abi, contract.address),
});
}
else{
setInfo({ ...intialInfo, status: "You need to be on the Ethereum testnet."});
}
}
else{
setInfo({ ...intialInfo, status: "You need metamask."});
}
};
const initOnChange = () => {
if(window.ethereum){
window.ethereum.on("accountsChanged", () =>{
window.location.reload();
});
window.ethereum.on("chainChanged", () =>{
window.location.reload();
});
}
};
const getDrops = async() => {
setDrops(prevState => ({
...prevState,
loading: true,
}));
info.contract.methods
.getDrops()
.call()
.then((result) => {
console.log(result);
setDrops({
loading: false,
list: result,
});
})
.catch((err) => {
console.log(err);
setDrops(intialDropState);
});
};
useEffect(() => {
init();
initOnChange();
}, []);
return (
<div>
<button onClick={() => getDrops()}>Get Drops </button>
{drops.loading ? <p>Loading</p> : null}
</div>
);
};
export default DropList;
【问题讨论】:
-
您没有显示
info的来源。可能该变量尚未初始化,或者它根本没有任何contract,或者contract没有任何方法。 -
您能否使用有关该信息变量的更多信息来编辑您的问题?看起来问题就在那里
标签: javascript html reactjs react-native smartcontracts