【问题标题】:在 React 中使用来自 MetaMask 的 web3
【发布时间】:2018-07-21 22:51:50
【问题描述】:

我正在尝试在 React js 应用程序中使用 MetaMask 中的 web3,如下所示:

import Web3 from 'web3';

    componentDidMount(){
            if (typeof web3 !== 'undefined') {
                console.log(web3.currentProvider);
                    // Use Mist/MetaMask's provider
                    var web3js = new Web3(web3.currentProvider);

                    web3.version.getNetwork((err, netId) => {
                    switch (netId) {
                        case "1":
                            console.log('This is mainnet')
                            break
                        case "2":
                            console.log('This is the deprecated Morden test network.')
                            break
                        case "3":
                            console.log('This is the ropsten test network.')
                            break
                        case "4":
                            console.log('This is the Rinkeby test network.')
                            break
                        case "42":
                            console.log('This is the Kovan test network.')
                            break
                        default:
                            console.log('This is an unknown network.')
                    }
                })
            } else {
                    console.log('No web3? You should consider trying MetaMask!')
            }           
        }

这是我在 chrome 的开发控制台中得到的输出:

很明显,在某些时候,MetaMask 根据前两行正确定义了 web3,但随后 react 会抛出一个错误,指出 web3 没有为它出现在 if(typeof web3 !== 'undefined') 中的实例定义。我尝试过的所有操作都会导致相同的错误或 web3 无法加载。

【问题讨论】:

    标签: reactjs web3js web3 metamask


    【解决方案1】:

    您应该在浏览器中使用像 MetaMask 这样的 web3 提供程序。 这是我用于 web3 检测的脚本:

    window.addEventListener('load', function () {
        if (typeof web3 !== 'undefined') {        
            window.web3 = new Web3(window.web3.currentProvider)
    
            if (window.web3.currentProvider.isMetaMask === true) {
                window.web3.eth.getAccounts((error, accounts) => {
                    if (accounts.length == 0) {
                        // there is no active accounts in MetaMask
                    }
                    else {
                        // It's ok
                    }
                });
            } else {
                // Another web3 provider
            }
        } else {
            // No web 3 provider
        }    
    });
    

    【讨论】:

      【解决方案2】:

      请注意,截至 2018 年 11 月,有一个 breaking change to MetaMask,其中 MetaMask 将不再自动将 web3 注入浏览器。相反,用户必须通过接受由 window.ethereum.enable() 创建的提示对话框来授予 DApp 对其帐户的访问权限。请参阅以下代码,了解如何在现代 DApp 浏览器和旧版 DApp 浏览器中处理 MetaMask。

      // Modern DApp Browsers
      if (window.ethereum) {
         web3 = new Web3(window.ethereum);
         try { 
            window.ethereum.enable().then(function() {
                // User has allowed account access to DApp...
            });
         } catch(e) {
            // User has denied account access to DApp...
         }
      }
      // Legacy DApp Browsers
      else if (window.web3) {
          web3 = new Web3(window.web3.currentProvider);
      }
      // Non-DApp Browsers
      else {
          alert('You have to install MetaMask !');
      }

      【讨论】:

        【解决方案3】:

        致想要解决此问题的新读者,截至January 2021, Metamask has removed it's injected window.web3 API。要使用将您的应用连接到 Metamask,我会尝试这样的操作

        export const connectWallet = async () => {
          if (window.ethereum) { //check if Metamask is installed
                try {
                    const address = await window.ethereum.enable(); //connect Metamask
                    const obj = {
                            connectedStatus: true,
                            status: "",
                            address: address
                        }
                        return obj;
                     
                } catch (error) {
                    return {
                        connectedStatus: false,
                        status: "? Connect to Metamask using the button on the top right."
                    }
                }
                
          } else {
                return {
                    connectedStatus: false,
                    status: "? You must install Metamask into your browser: https://metamask.io/download.html"
                }
              } 
        };
        

        this tutorial on creating an NFT Minter with React,您还可以学习如何通过Metamask调用智能合约函数和签署交易!祝你好运:)

        【讨论】:

          【解决方案4】:

          感谢这个问题的其他答案。我参考他们在我的项目中创建这个钩子。

          
          export function useCheckMetaMaskInstalled() {
            const [installed, setInstalled] = useState(false);
            useEffect(() => {
              if (window.ethereum) {
                setInstalled(true);
              }
            }, []);
            return installed;
          }
          

          【讨论】:

            猜你喜欢
            • 1970-01-01
            • 2019-08-03
            • 1970-01-01
            • 2019-07-05
            • 2019-05-24
            • 1970-01-01
            • 1970-01-01
            • 2021-07-30
            • 2021-08-23
            相关资源
            最近更新 更多