编码React函数以从第三方网站获取并显示数据
P粉823268006
2023-08-29 21:41:15
<p>帮助我从区块链中获取信息并在浏览器中显示。我想知道如何在React中调用这个thirdweb函数。
下面的代码是用于在我们的系统中创建用户的Solidity代码。</p>
<pre class="brush:php;toolbar:false;">function createUser(string memory _userId, string memory _fName, string memory _lName, string memory _mobile, string memory _dob, uint256 _age, string memory _nationality, string memory _gender) public {
if(!chkexisitinguserId(_userId)){
users[_userId] = User(_fName, _lName, _mobile, _dob, _age,_nationality,_gender);
noofUser++;
allUserId[k] = _userId;
k++;
}
}
function getUser(string memory _userId) public view returns (string memory, string memory, string memory, string memory, uint256, string memory, string memory) {
User memory user = users[_userId];
return (user.fName, user.lName, user.mobile, user.dob, user.age, user.nationality, user.gender);
}</pre>
<p>下面的代码是与智能合约交互的thirdweb库代码。下面的代码存储在refer.js文件中。</p>
<pre class="brush:php;toolbar:false;">import { useContract, useContractWrite } from "@thirdweb-dev/react";
export default function Component() {
const { contract } = useContract("0xBB417720eBc8b76AdeAe2FF4670bbc650C3E791f");
const { mutateAsync: createUser, isLoading } = useContractWrite(contract, "createUser")
const call = async () => {
try {
const data = await createUser([ "John0312", "John", "s", "8090890367", "03-11-2000", 20, "India", "M" ]);
console.info("contract call successs", data);
} catch (err) {
console.error("contract call failure", err);
}
}
}
export default function Component() {
const { contract } = useContract("0xBB417720eBc8b76AdeAe2FF4670bbc650C3E791f");
const { data, isLoading } = useContractRead(contract, "getUser", _userId)
}</pre>
<p>智能合约已部署在thirdweb上并尝试访问它。我卡在如何从app.js中调用这个"call"异步函数。</p>
<pre class="brush:php;toolbar:false;">import React, { useEffect } from 'react'
function App(){
const handleclick = async (e) => {
await call();
}
return (
<button onClick={handleclick}>click me</button>
)
}
export default App</pre>
<p>它生成了类似未定义函数call()的错误。</p>
我会创建一个新的钩子 (
useCall.js
),它的作用仅仅是实例化useContract
和useContractWrite
钩子,然后为您在任何组件中使用定义call()
方法。在这个例子中,
call()
是从钩子中返回的唯一内容。它被包裹在useCallback
中,以确保它只在createUser
被定义时才被定义。现在在任何组件中,您可以使用这个钩子并获取
call()
函数: