通过Web3.js致电和访问智能合约功能?
我需要知道如何通过Web3.js将这些方法调用到我的前端,该方法在React以及结构数据中。
// SPDX-License-Identifier: MIT
pragma solidity >=0.4.22 <0.9.0;
struct customer {
uint256 amount;
}
contract Lottery {
address payable public admin;
address payable[] public add;
mapping(address => customer) public data;
function getBalance() public view onlyOwner returns (uint256) {
return address(this).balance/1 ether;
}
function getter() view public returns (uint)
{
return add.length;
}
这是我正在使用的反应码,但我无法调用其他功能(数组长度)
useEffect(()=>{
const getMemebers=async()=>{
const admin=await web3Api.contract.admin({
from:account
});
setAccount(admin);
}
web3Api.contract && getMemebers();
},[web3Api.web3])
I need to know how can I call these methods through web3.js into my frontend which is in react and also the structure data.
// SPDX-License-Identifier: MIT
pragma solidity >=0.4.22 <0.9.0;
struct customer {
uint256 amount;
}
contract Lottery {
address payable public admin;
address payable[] public add;
mapping(address => customer) public data;
function getBalance() public view onlyOwner returns (uint256) {
return address(this).balance/1 ether;
}
function getter() view public returns (uint)
{
return add.length;
}
Here's the code of React that I am using which is working but I am not able to call other functions(array length)
useEffect(()=>{
const getMemebers=async()=>{
const admin=await web3Api.contract.admin({
from:account
});
setAccount(admin);
}
web3Api.contract && getMemebers();
},[web3Api.web3])
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
假设您已经在您的SRC文件夹中设置了Web3.js文件,我看到的唯一问题是您在使用effect中调用异步函数,这总是一个坏主意。
取而代之的是,您可以定义一个不同的异步函数,并通常在使用效果中调用。如果您为其分配任何状态,它将为您刷新DOM。我没有足够的信息来提供更好的解决方案,但是我添加了我编写的类似代码,哪些代码有效
Assuming you've web3.js file set up in your src folder, the only issue I see is you're calling an async function in useEffect which is always a bad idea.
Instead you can define a different async function and call that normally in useEffect. If you assign any state to it, it'll refresh the dom for you. I don't have enough information to provide better solution but I'm adding a similar code which I wrote and which worked