Web3:在新 ethers.Contract 之后无法读取 null 的属性

Web3: Cannot read properties of null after new ethers.Contract

我正在尝试在实例化智能合约后立即使用它。但是,我得到一个错误:

Uncaught (in promise) TypeError: Cannot read properties of null (reading 'call')

我还以为刚实例化就不能访问函数了,结果好像不是。还能是什么呢?有人遇到过类似的问题吗?

当前代码:

import React, { useEffect, useState } from 'react';
import Head from 'next/head';

import { useWeb3React } from '@web3-react/core';
import NFTCollectionArtifact from 'artifacts/contracts/NFTCollection.sol/NFTCollection.json';
import { Contract, ethers, Signer } from 'ethers';
import { Provider } from '@openmint/utils/provider';

export const Index = () => {
  const context = useWeb3React<Provider>();
  const { library } = context;

  const [contractInstance, setContractInstance] = useState<Contract | undefined>();
  const [signer, setSigner] = useState<Signer>();
  const [name, setName] = useState<String>('');

  useEffect(() => {

    const address = '0x5FbDB2315678afecb367f032d93F642f64180aa3';
    const nftCollection = new ethers.Contract(
      address,
      NFTCollectionArtifact.abi,
      signer
    );

    setContractInstance(nftCollection);
  }, []);

  useEffect(() => {
    if(!contractInstance) return;

    const setContractName = async () => {
      try{
        console.log(await contractInstance?.name());
        setName(await contractInstance?.name());
      } catch(e){
        console.error('my error', e);
      }
    }
  
    setContractName();
  }, [contractInstance]);

  useEffect((): void => {
    if (!library) {
      setSigner(undefined);
      return;
    }

    setSigner(library.getSigner());
  }, [library]);

  return (
    <>
      <Head>
        <title>Preview NFTs</title>
      </Head>
    </>
  );
};

export default Index;

确保您的环境配置中的帐户设置正确。在我的例子中,这是因为我在使用 ethers + hardhat 时在我的 .env 中设置了额外的 WALLET_PRIVATE_KEY= 行。

好的,我仍然不明白以下解决方案为何有效的全貌,但如果有人遇到类似问题,这对我有用:

useEffect((): void => {
    if (!contractInstance) {
      return;
    }

    async function getStatus(MyContract: Contract): Promise<void> {
      const name = await MyContract.name();

      const newStatus: StatusInterface = {
        ...status,
        name
      };

      console.log('newStatus', newStatus);
      if (!isEqual(status, newStatus)) {
        setStatus(newStatus);
      }
    }

    getStatus(contractInstance);
  }, [contractInstance, status, account]);
  • 只有在有差异时才更改状态
  • 将合约作为函数的 prop 传递

我的理解是这是一个范围问题。