我是新来的反应。我创建了一个类组件,并且有一个构造函数。
我在构造函数中创建了this.state。
在componentDidMount上,我调用了几个函数,并在这些函数中创建了const。
对于那些在构造函数之外声明并在componentDidMount()函数中创建和调用的变量,我可以使用componentDidMount()吗?
当我试图在另一个函数中使用这样的变量时,我得到了一个错误。
我的代码如下:
class App extends Component {
constructor(props) {
super(props);
this.state = {
web3: null,
network: "",
account: 0x0
};
}
componentDidMount = async () => {
await this.loadWeb3();
};
loadWeb3 = async () => {
const web3 = await getWeb3();
const accounts = await web3.eth.getAccounts();
this.setState({ account: accounts[0] });
const networkId = await web3.eth.net.getId();
this.setState({ networkId });
this.setState({ web3 });
console.log(web3); //
console.log(networkId); //got sucessfully console log over here
await this.setNetwork();
};
setNetwork = async () => {
let networkName,
that = this;
await this.state.web3.eth.net.getNetworkType(function(err, network) {
switch (network) {
case "main":
networkName = "Main";
break;
case "morden":
networkName = "Morden";
break;
case "ropsten":
networkName = "Ropsten";
break;
case "private":
networkName = "Ganache";
break;
default:
networkName = this.state.networkId; //but got error over here "Unhandled Rejection (TypeError): Cannot read property 'state' of undefined"
}
that.setState({
network: networkName
});
console.log(this.state.network);
});
};在setNetwork()默认开关情况下,我得到了以下错误
未处理的拒绝(TypeError):无法读取未定义的属性“状态”
发布于 2019-09-30 09:37:44
发生错误是因为并不是所有的代码都有箭头函数..。
await this.state.web3.eth.net.getNetworkType(function(err, network) {具体来说,这一部分是放松函数的this .
我会把它改写成
await this.state.web3.eth.net.getNetworkType((err, network) => {或者使用在函数中高级定义的that,只是您试图在交换机上访问的this不再是以前的this了。使用箭头函数将为您解决“上下文”问题。
发布于 2019-09-30 09:42:00
根据文档
承诺返回字符串:
你可以用:
const network = await this.state.web3.eth.net.getNetworkType();
setState({ network });https://stackoverflow.com/questions/58164978
复制相似问题