为自定义钩子初始化 useContext 类型

时间:2021-05-27 21:09:18

标签: reactjs typescript react-hooks

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

我觉得特别奇怪的是,我收到消息: <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN" "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd"> <html xml:lang="en-US" xmlns="http://www.w3.org/1999/xhtml"> <head> <meta content="IE=8" http-equiv="X-UA-Compatible"/> <ALL THE CONTENT>Too much to paste in the answer</ALL THE CONTENT> </html> ,虽然它显然是 APIProps 的一部分,对吗?我的猜测是这是因为上下文的初始化,有人可以帮我吗?

谢谢!

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

Property 'createFlow' does not exist on type 'APIProps | null'
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;

1 个答案:

答案 0 :(得分:1)

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

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>;
};