我很难弄清楚为了让我的自定义钩子与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>
}
发布于 2021-05-27 21:20:21
null
上不存在createFlow
,并且您声明您的类型可以为空。在使用上下文之前,必须断言上下文值不为空:
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>;
};
https://stackoverflow.com/questions/67730020
复制相似问题