簡體   English   中英

如何從 React JS 訪問智能合約功能?

[英]How to access smart contract functions from React JS?

我正在制作彩票合同,但當我嘗試訪問我的經理方法時,我在 ReactJS 中收到此錯誤。[.[在此處輸入圖片描述][1]][1] 請幫助我解決問題。 我已經開發了我的合同,但在將它連接到前端時遇到問題。

這是錯誤。 [1]: https://i.stack.imgur.com/QFc2o.png

App.js文件

 import detectEthereumProvider from "@metamask/detect-provider"; // import { loadContract } from "./utils/LoadContracts"; import Web3 from "web3"; import lottery from "./lottery"; import { useEffect, useState } from "react"; function App() { const [balance, setBalance] = useState(""); const [changedAccount, setChangedAccount] = useState([]); const loader = async() => { let provider = await detectEthereumProvider(); let web3 = new Web3(provider); return { provider, web3 }; }; useEffect(async() => { let newLoad = await loader(); let account = await newLoad.web3.eth.getAccounts(); setChangedAccount(account); }, []); useEffect(async() => { let newLoad = await loader(); newLoad.provider.on("accountsChanged", function(accounts) { let newAccount = accounts; if (newAccount) { setChangedAccount(newAccount); } }); }, []); useEffect(async() => { let newLoad = await loader(); let accountBal = changedAccount.length > 0 && (await newLoad.web3.eth.getBalance(changedAccount[0])); setBalance(accountBal); }, [changedAccount]); useEffect(async() => { let newLoad = await loader(); let account = await newLoad.web3.eth.getAccounts(); setChangedAccount(account); const manager = await lottery.methods.manager().call(); }, []); return ( < div > < p > Account address { changedAccount[0] }, Its balance is: { balance } < /p> < /div> ); } export default App;

lottery.js(包含ABI和合約地址)

 import Web3 from "web3"; let web3 = new Web3(); const address = "0xBEbdb8eC68A5803d0f5E93bACe9EB9E4227f5A20"; const abi = [{ inputs: [], stateMutability: "nonpayable", type: "constructor" }, { inputs: [], name: "manager", outputs: [{ internalType: "address", name: "", type: "address" }], stateMutability: "view", type: "function", }, { inputs: [{ internalType: "uint256", name: "", type: "uint256" }], name: "players", outputs: [{ internalType: "address", name: "", type: "address" }], stateMutability: "view", type: "function", }, { inputs: [], name: "enter", outputs: [], stateMutability: "payable", type: "function", }, { inputs: [], name: "getBalance", outputs: [{ internalType: "uint256", name: "", type: "uint256" }], stateMutability: "view", type: "function", }, { inputs: [], name: "pickWinner", outputs: [], stateMutability: "nonpayable", type: "function", }, { inputs: [], name: "getPlayers", outputs: [{ internalType: "address[]", name: "", type: "address[]" }], stateMutability: "view", type: "function", }, ]; export default new web3.eth.Contract(abi, address);

您尚未在此行的 lottery.js 中提供任何“提供者”

let web3 = new Web3();

這沒有給你正確的合同實例,因此你無法訪問它的方法

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM