我在一个简单的react应用程序上遇到了这个问题。我正试图使用";连接";按钮,但当我点击该按钮时,控制台显示一个错误,说";错误:不变量失败:否<Web3React提供程序/>找到">
正如您所看到的,我向getLibrary函数添加了一个控制台,但它没有进行日志记录,因此,该函数从未被调用。
import "./App.css";
import React from "react";
import { Web3ReactProvider, useWeb3React } from "@web3-react/core";
import { Web3Provider } from "@ethersproject/providers";
import { InjectedConnector } from "@web3-react/injected-connector";
const injected = new InjectedConnector({
supportedChainIds: [1, 3, 4, 5, 42],
});
function getLibrary(provider) {
console.log("getting library")
const library = new Web3Provider(provider)
library.pollingInterval = 12000
return library
}
const App = () => {
const { active, account, library, connector, activate, deactivate } =
useWeb3React();
async function connect() {
console.log("connecting");
try {
await activate(injected);
} catch (ex) {
console.log(ex);
}
}
async function disconnect() {
try {
deactivate();
} catch (ex) {
console.log(ex);
}
}
return (
<Web3ReactProvider getLibrary={getLibrary}>
<div className="App">
{!active ? <button onClick={connect}>Connect</button> : <button onClick={connect}>Disconnect</button>}
</div>
</Web3ReactProvider>
);
}
这里的问题是,您试图在定义上下文提供程序的同一组件中调用use钩子。将Provider移高一级到调用App
的组件中,或者将钩子和剩余逻辑移低一级到新组件中。