Await 一直在等待 - React, React Router

Await Keeps on Waiting - React, React Router

我正在使用 Truffle React Box。当我使用 React Router 打开一个组件时。在 ComponentDidMount 中等待没有 return 任何东西。但是,刷新页面后,它工作正常。

这是我的代码:

componentDidMount = async () => {
    try {
        console.log("1");
        const web3 = await getWeb3();
        console.log("2")
        const accounts = await web3.eth.getAccounts();
        const Contract = truffleContract(PrototypeStateContract);
        Contract.setProvider(web3.currentProvider);
        const instance = await Contract.deployed();
        this.setState({ web3, accounts, contract: instance });
    } catch (error) {
      alert(
        `Failed to load web3, accounts, or contract. Check console for details.`
      );
      console.log(error);
    }
};

使用react router "Link to"访问组件时,只打印“1”。

刷新同一页时,“1”和“2”都按预期打印。

我该如何解决这个问题?

对 getWeb3.js 进行这些更改后问题已解决。

import Web3 from "web3";

const getWeb3 = () =>
  new Promise( async(resolve, reject) => {
    // Wait for loading completion to avoid race conditions with web3 injection timing.
      // Modern dapp browsers...
      if (window.ethereum) {
        const web3 = new Web3(window.ethereum);
        try {
          // Request account access if needed
          await window.ethereum.enable();
          // Acccounts now exposed
          resolve(web3);
        } catch (error) {
          reject(error);
        }
      }
      // Legacy dapp browsers...
      else if (window.web3) {
        // Use Mist/MetaMask's provider.
        const web3 = window.web3;
        console.log("Injected web3 detected.");
        resolve(web3);
      }
      // Fallback to localhost; use dev console port by default...
      else {
        const provider = new Web3.providers.HttpProvider(
          "http://127.0.0.1:9545"
        );
        const web3 = new Web3(provider);
        console.log("No web3 instance injected, using Local web3.");
        resolve(web3);
      }

  });

export default getWeb3;

我已经删除了事件侦听器,因为 window 在从 react-router Link 访问时不会加载。