【发布时间】:2021-10-22 04:49:07
【问题描述】:
运行命令 NPM Start 时出现错误。该文件是在 PanCakeSwap 前端创建的,我已经尝试修复了一段时间,感谢您的帮助:)
这是我的 App.js 代码:
import React, { useState, useEffect } from "react";
import SimpleStorageContract from "./contracts/SimpleStorage.json";
import getWeb3 from "./getWeb3";
import BlockchainContext from './BlockchainContext.js';
import "./App.css";
function App() {
const [storageValue, setStorageValue] = useState(undefined);
const [web3, setWeb3] = useState(undefined);
const [accounts, setAccounts] = useState([]);
const [contract, setContract] = useState([]);
useEffect(() => {
try {
// Get network provider and web3 instance.
const web3 = await getWeb3();
// // Use web3 to get the user's accounts.
const accounts = await web3.eth.getAccounts();
// // Get the contract instance.
const networkId = await web3.eth.net.getId();
const deployedNetwork = SimpleStorageContract.networks[networkId];
const contract = new web3.eth.Contract(
SimpleStorageContract.abi,
deployedNetwork && deployedNetwork.address,
);
// Set web3, accounts, and contract to the state, and then proceed with an // example of interacting with the contract's methods.
setWeb3(web3);
setAccounts(accounts);
setContract(contract);;
this.setState({ web3, accounts, contract: instance } catch (error) {
// Catch any errors for any of the above operations.
alert(
`Failed to load web3, accounts, or contract. Check console for details.`,
);
console.error(error);
const init = async() => {
}
init();
}, []);
useEffect(() => {
const load = async () => {
// Stores a given value, 5 by default.
await contract.methods.set(5).send({ from: accounts[0] });
// // Get the value from the contract to prove it worked.
const response = await contract.methods.get().call();
// // Update state with the result.
setStorageValue(response);
}
if(typeof web3 !== 'undefined'
&& typeof account !== 'undefined'
&& typeof contract !== 'undefined'{
load();
}
}, [web3, accounts, contract]);
if(typeof web3 === 'undefined') {
return <div>Loading Web3, account, and contract...</div>;
}
return (
<div className="App">
<BlockchainContext.Provider value={{web3, accounts, contract}}>
<h1>Good to Go!</h1>
<p>Your Truffle Box is installed and ready.</p>
<h2>Smart Contract Example</h2>
<p>
If your contracts compiled and migrated successfully, below will show
a stored value of 5 (by default).
</p>
<p>
Try changing the value stored on <strong>line 42</strong> of App.js.
</p>
<div>The stored value is: {storageValue}</div>
</BlockchainContext.Provider>
</div>
);
}
export default App;
我得到的错误是: ** 编译失败。
./src/App.js 第 17:23 行:解析错误:不能在异步函数之外使用关键字 'await'
15 |尝试 { 16 | // 获取网络提供者和 web3 实例。
17 |常量 web3 = 等待 getWeb3(); | ^ 18 |
19 | // // 使用 web3 获取用户的帐号。 20 |常量帐户 = 等待 web3.eth.getAccounts(); **
【问题讨论】:
-
你需要查看 js 中的 async-await 来解决它,而且你的代码看起来真的很不干净,它让那里的东西理解起来很复杂。
标签: node.js typescript fork truffle npm-start