Reactjs 在构造函数外部声明的常量的React setState

Reactjs 在构造函数外部声明的常量的React setState,reactjs,state,Reactjs,State,我是新来的。我创建了一个类组件,其中有一个构造函数 我在构造函数中创建了这个.state 在componentDidMount上,我调用了几个函数,并在这些函数中创建常量 对于在构造函数外部声明并在componentDidMount()函数中创建和调用的变量,我是否可以使用this.setState({}) 我试图在另一个函数中使用这些变量时出错 我的代码如下: class App extends Component { constructor(props) { super(pr

我是新来的。我创建了一个类组件,其中有一个构造函数

我在构造函数中创建了这个.state

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

对于在构造函数外部声明并在
componentDidMount()函数中创建和调用的变量,我是否可以使用
this.setState({})

我试图在另一个函数中使用这些变量时出错

我的代码如下:

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):无法读取未定义的属性“state”

发生错误是因为并非所有代码都具有箭头函数

  await this.state.web3.eth.net.getNetworkType(function(err, network) {
具体地说,这一部分正在松开函数的

我会把它重新写下来

await this.state.web3.eth.net.getNetworkType((err, network) => {
或者使用您在函数的上方定义的
,只是您试图在交换机上访问的
不再是您以前使用的
。使用箭头函数将为您解决“上下文”问题,如下所示:

承诺返回字符串:

您可以使用:

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

setState({ network });

感谢@Alejandro,所以我想澄清一下,如果我没有在这个.state{}中声明一个变量,并且在正常函数(比如networkId)中声明为const,那么在我的例子中,我仍然可以这样做.setState({networkId});并将其用作this.state.networkId;在同一组件的任何其他函数中?@urjitonrails否。您只能对
此.state
中定义的键使用
setState()
。如果未在
此.state
中定义它,即普通变量,则不会导致重新渲染。