我无法访问
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;
因为属性
account
在类型null
中不存在,你可以定义一个属性处于初始状态的initialDataContextProps
对象,并从null
泛型中删除unioncreateContext
,例如:
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