对外部构造函数声明的const的setState进行反应

时间:2019-09-30 09:25:22

标签: reactjs state

我是React的新手。我创建了一个类组件,并且有一个构造函数。

我在构造函数中创建了this.state。

componentDidMount上,我调用了几个函数,并在这些函数中创建了const。

我可以对在构造函数外部声明并在this.setState({})函数中创建和调用的变量使用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):无法读取未定义的属性“状态”

2 个答案:

答案 0 :(得分:1)

发生错误是因为并非所有代码都具有箭头功能...

  await this.state.web3.eth.net.getNetworkType(function(err, network) {

特别是这部分正在失去功能的this ...

我将其重写为

await this.state.web3.eth.net.getNetworkType((err, network) => {

或使用您已在函数中定义上半部的that,只是您尝试在交换机上访问的this不再是您以前拥有的this 。使用箭头功能可以为您解决“上下文”问题

答案 1 :(得分:1)

根据docs

  

Promise返回字符串:

您可以使用:

const network = await this.state.web3.eth.net.getNetworkType();

setState({ network });