我正在尝试在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 抛出一个错误,指出未对if(typeof web3!=='undefined')中出现的实例定义web3。我尝试过的所有操作都会导致相同的错误,或者Web3无法加载。
最佳答案
请注意,截至2018年11月,已有一个breaking change to MetaMask,MetaMask将不再自动将web3注入(inject)浏览器。相反,用户必须通过接受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 !');
}
关于reactjs - 在React中使用MetaMask的web3,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/48735118/