正在初始化自定义挂钩的useContext类型



我很难弄清楚需要哪些类型才能使我的自定义挂钩与useContext一起工作。我觉得我已经尝试了所有可能的组合,但这就像一场"打地鼠"游戏,只要我一个部分工作,另一个部分就休息。

我觉得特别奇怪的是,我收到了一条消息:Property 'createFlow' does not exist on type 'APIProps | null',尽管它显然是APIProps的一部分,对吧?我的猜测是,这是因为上下文的初始化,有人能帮我吗?

谢谢!

代码相对较短,所以我会发布所有内容以方便复制粘贴测试:

import axios, { AxiosResponse } from "axios";
import React, { useState, useContext, createContext, FC } from "react";
interface APIProps {
project?: {};
setProject?: React.Dispatch<React.SetStateAction<{}>>;
createProject?: (project: {}) => Promise<AxiosResponse<any>>;
createFlow?: (
projectId: string,
patchData: {
op: string;
flow: {
name: string;
description: string;
};
}
) => Promise<AxiosResponse<any>>;
}
const DBContext = createContext<APIProps | null>(null); // what to put here
export const useAPI = () => useContext(DBContext);
const DBProvider: FC = ({ children }) => {
const [project, setProject] = useState({});
/**
* creates new project entry in the db, returns projectId on success
* @param {*} project object with name, description, provider
*/
const createProject = (project: { name: string; description: string }) =>
axios.post(`http://localhost:3000/projects`, project);
const createFlow = (
projectId: string,
patchData: { op: string; flow: { name: string; description: string } }
) => axios.patch(`http://localhost:3000/projects/${projectId}`, patchData);
const value = { project, setProject, createProject, createFlow };
return <DBContext.Provider value={value}>{children}</DBContext.Provider>;
};
export default DBProvider;
const MyComponent:FC<Props> = ({props}) => {
// I can't figure out how to get this part to work!
// Property 'createFlow' does not exist on type 'APIProps | null'
const { createFlow }: APIProps | null = useAPI();
return
<button onClick={
() => createFlow("id", {op: "", flow: {name: "", description: ""}})
}>Click</button>
}

createFlownull上不存在,并且您声明您的类型可以为null。在使用它之前,您必须断言您的上下文值不是null:

const MyComponent: FC<Props> = ({ props }) => {
// I can't figure out how to get this part to work!
// Property 'createFlow' does not exist on type 'APIProps | null'
const api = useAPI();
return api && <button
onClick={() =>
api.createFlow("id", { op: "", flow: { name: "", description: "" } })
}
>
Click
</button>;
};

相关内容

最新更新