4

我正在使用 nextjs + reactjs + typescript。没有打字稿可以正常工作,但是在使用打字稿时我得到了这个错误。顺便说一句,我在useMemo这里使用,但我尝试在函数之外对其进行初始化。在这两种情况下,我都遇到了同样的错误。

这是我目前正在使用的代码片段

const INFURA_ID = process.env.REACT_APP_INFURA_ID;

const initWeb3 = (provider: any) => {
  const web3 = new Web3(provider);

  web3.eth.extend({
    methods: [
      {
        name: "chainId",
        call: "eth_chainId",
        outputFormatter: web3.utils.hexToNumber as any,
      },
    ],
  });

  return web3;
};

export function Web3UtilityProvider() {
  const [walletAddress, setWalletAddress] = useState(null);
  const { user, authDispatch } = useAuth();

  const dAppClient = useMemo(() => new DAppClient({ name: "Beacon Docs" }), []);

  const web3Modal = useMemo(() => {
    return new Web3Modal({
      // network: "mainnet", // optional
      cacheProvider: true, // optional
      providerOptions: {
        walletconnect: {
          package: WalletConnectProvider, // required
          options: {
            infuraId: INFURA_ID,
          },
        },
        // torus: {
        //   package: Torus,
        // },
        fortmatic: {
          package: Fortmatic,
          options: {
            key: process.env.REACT_APP_FORTMATIC_KEY,
          },
        },
        authereum: {
          package: Authereum,
        },
        bitski: {
          package: Bitski,
          options: {
            clientId: process.env.REACT_APP_BITSKI_CLIENT_ID,
            callbackUrl:
              window.location.href + "bitski-callback.html",
          },
        },
      },
    });
  }, []);

  const logoutOfWeb3Modal = useCallback(async () => {
    async () => {
      web3Modal.clearCachedProvider();
      setTimeout(() => {
        typeof window !== "undefined" && window.location.reload();
      }, 1);
    };
  }, [web3Modal]);

  const loadWeb3Modal = useCallback(async () => {
    const provider = await web3Modal.connect();

    if (!provider?.on) {
      return;
    }

    const web3 = initWeb3(provider);

    const accounts = await web3.eth.getAccounts();

    provider.on("close", () => {
      logoutOfWeb3Modal();
    });

    provider.on("accountsChanged", async (accounts: any) => {
      console.log("accountsChanged", accounts);
      if (!accounts || !accounts.length) {
        return;
      }
    });
  }, []);

  return (
    <Web3Context.Provider
      value={{
       logoutOfWeb3Modal,
       loadWeb3Modal
      }}
    >
      {children}
    </Web3Context.Provider>
  );
}

错误png

4

1 回答 1

1

实际上,这个错误与js或ts无关;由于 CSR,它正在使用 reactjs 应用程序,但在我的情况下,我使用的是 nextjs,并且由于 SSR,该窗口对象未定义。所以,为了解决这个错误,我简单地使用了回退(即 useEffect)。

于 2021-10-29T07:04:12.280 回答