在学习了一个关于可靠性的教程后,我开始在前端工作,并最终使用了这个error
它不让我获取问候语,但我可以设置问候语除了获取问候语,它不会让我看到它,即使我将问候语设置为其他内容,我在控制台中看不到它,这里的错误是Solidity tutorial
这是我的实心度代码
pragma solidity ^0.8.4;
import "hardhat/console.sol";
contract Greeter {
string greeting;
constructor(string memory _greeting) {
console.log("Deploying a Greeter with greeting:", _greeting);
greeting = _greeting;
}
function greet() public view returns (string memory) {
return greeting;
}
function setGreeting(string memory _greeting) public {
console.log("Changing greeting from '%s' to '%s'", greeting, _greeting);
greeting = _greeting;
}
}
下面是我的react代码:
import './App.css';
import { useState } from 'react';
import { ethers } from 'ethers'
import Greeter from './artifacts/contracts/Greeter.sol/Greeter.json'
// Update with the contract address logged out to the CLI when it was deployed
const greeterAddress = "0xf39Fd6e51aad88F6F4ce6aB8827279cffFb92266"
function App() {
// store greeting in local state
const [greeting, setGreetingValue] = useState()
// request access to the user's MetaMask account
async function requestAccount() {
await window.ethereum.request({ method: 'eth_requestAccounts' });
}
// call the smart contract, read the current greeting value
async function fetchGreeting() {
if (typeof window.ethereum !== 'undefined') {
const provider = new ethers.providers.Web3Provider(window.ethereum)
const contract = new ethers.Contract(greeterAddress, Greeter.abi, provider)
try {
const data = await contract.greet()
console.log('data: ', data)
} catch (err) {
console.log("Error: ", err)
}
}
}
// call the smart contract, send an update
async function setGreeting() {
if (!greeting) return
if (typeof window.ethereum !== 'undefined') {
await requestAccount()
const provider = new ethers.providers.Web3Provider(window.ethereum);
const signer = provider.getSigner()
const contract = new ethers.Contract(greeterAddress, Greeter.abi, signer)
const transaction = await contract.setGreeting(greeting)
await transaction.wait()
fetchGreeting()
}
}
return (
<div className="App">
<header className="App-header">
<button onClick={fetchGreeting}>Fetch Greeting</button>
<button onClick={setGreeting}>Set Greeting</button>
<input onChange={e => setGreetingValue(e.target.value)} placeholder="Set greeting" />
</header>
</div>
);
}
export default App;
任何建议都会对你有所帮助
发布于 2021-05-26 18:24:22
您需要插入属性值
value = {greeting}
在输入中:
<input onChange={e => setGreetingValue(e.target.value)}
placeholder="Introduce uno nuevo"
value={greeting}
/>
也可以用两个引号初始化useState ():
const [greeting, setGreetingValue] = useState ('')
你现在可能会遇到一个关于metamask nonce的问题,它会告诉你它太高了,就像下面这样的消息错误:
Nonce too high. Expected nonce to be 1 but got 2
您将在metamask中重置帐户,或导入新帐户。
https://stackoverflow.com/questions/67628454
复制相似问题