TypeScript 中的自定义 React 挂钩 - 没有调用签名

Bil*_*ill 1 typescript reactjs

我有这个自定义钩子来调用 API

import { useState, useCallback } from 'react';

interface OptionsShape {
  method: 'GET' | 'POST';
}

interface InitStateShape {
  data: any;
  success: boolean;
  loading: boolean;
  error: Error | null;
}

const useAPI = (initialData = null) => {
  const initialState: InitStateShape = {
    data: initialData,
    success: false,
    loading: false,
    error: null,
  };

  const [response, setResponse] = useState(initialState);

  const callAPI = async (URL: string, options: OptionsShape) => {
    setResponse({ ...response, success: false, loading: true });

    try {
      const response = await fetch(URL, options);
      if (response.status < 200 || response.status >= 300)
        throw new Error('Failed to fetch');
      const json = await response.json();
      setResponse({
        data: json,
        success: true,
        loading: false,
        error: null,
      });
    } catch (e) {
      setResponse({
        data: initialData,
        success: false,
        loading: false,
        error: e.message,
      });
    }
  };

  return [response, useCallback(callAPI, [])];
};

export { useAPI };
Run Code Online (Sandbox Code Playgroud)

我用它来称呼它

import { useAPI } from '../hooks/useAPI';
...
const [response, callAPI] = useAPI();
...
callAPI('https://api.mysite.com/test', { method: 'GET' });
Run Code Online (Sandbox Code Playgroud)

我在 callAPI 上收到的错误是:

This expression is not callable.
  Not all constituents of type '{ data: null; success: boolean; loading: boolean; error: null; } | ((URL: string, options: OptionsShape) => Promise<void>)' are callable.
    Type '{ data: null; success: boolean; loading: boolean; error: null; }' has no call signatures.ts(2349)
Run Code Online (Sandbox Code Playgroud)

Jon*_*lms 7

返回值被推断为数组而不是元组。您可以通过添加以下内容来更改as const

 return [response, useCallback(callAPI, [])] as const;
Run Code Online (Sandbox Code Playgroud)