“DataContextProps | 类型”上不存在属性“account”空'

问题描述 投票:0回答:1

我无法访问

account
或来自
DataContextProps
的任何其他财产。

上下文/Datacontext.tsx


interface DataContextProps {
    account: string;
    contract: any;
    loading: any;
    images: any[];
    imageCount: number;
    updateImages: () => Promise<void>;
    donateImageOwner: (id: string, DonateAmount: any) => Promise<void>;
};

const DataContext = createContext<DataContextProps | null>(null);

interface Props {
    children?: React.ReactNode;
  };

export const DataProvider: React.FC<Props> = ({ children }) => {
    const data = useProviderData();
    return <DataContext.Provider value={data}>{children}</DataContext.Provider>;
};

export const useData = () => useContext<DataContextProps | null>(DataContext);

标头.tsx

import Identicon from "identicon";
import React, { useEffect } from "react";
import { useData } from "../../contexts/DataContext";

function Header() {
  const { account } = useData();
  const [data, setData] = React.useState();
  useEffect(() => {
    if (account !== "0x0") {
      setData(new Identicon(account, 200).toString());
    }
  }, [account]);
  return ()
}
export default Header;
reactjs typescript truffle
1个回答
0
投票

因为属性

account
在类型
null
中不存在,你可以定义一个属性处于初始状态的
initialDataContextProps
对象,并从
null
泛型中删除union
createContext
,例如:

const initialDataContextProps = {
    account: "";
    contract: null;
    loading: null;
    images: [];
    imageCount: 0;
    updateImages: async () => {};
    donateImageOwner: async (id: string, DonateAmount: any) => {};
};

const DataContext = createContext<DataContextProps>(initialDataContextProps)
/* ...other code */
export const useData = () => useContext(DataContext); // no generics needed
© www.soinside.com 2019 - 2024. All rights reserved.