React TypeScript:自定义获取挂钩

时间:2019-10-04 07:14:56

标签: reactjs typescript

我正在尝试编写一个自定义的获取挂钩,但是我想我遗漏了一些东西。

import React, { useContext } from 'react';
import { Context } from "../components/context";

const fetchHook = async(url: string, bearer: string, method: string, body: any ) => {
    const { global } = useContext(Context) as {global: any};
    let headers = {'cache-control': 'no-cache', 'Content-Type': 'application/json' };
    if (bearer) headers = {...headers, ...{'Authorization': bearer}}
    if (method === 'GET') return await fetch(global.apiUrl + url, {method, headers});
    else return await fetch(global.apiUrl + url, {method, headers, body});
}

export { fetchHook }

即时消息错误为Line 5: React Hook "useContext" is called in function "fetchHook" which is neither a React function component or a custom React Hook function react-hooks/rules-of-hooks

更新:

import React, { useContext } from 'react';
import { Context } from "../components/context";


const useFetch = (url: string, bearer: string, method: string, body: any) => {

    const { global } = useContext(Context) as {global: any};
    let headers = {'cache-control': 'no-cache', 'Content-Type': 'application/json' };
    if (bearer) headers = {...headers, ...{'Authorization': bearer}}

    const [response, setResponse] = React.useState(null);
    const [error, setError] = React.useState(null);
    const apiUrl = global.apiUrl;

    React.useEffect(() => {
      const fetchData = async () => {
        try {
            let res; 
            if (method === 'GET') res = await fetch(apiUrl + url, {method, headers});
            else res = await fetch(global.apiUrl + url, {method, headers, body});
            setResponse(await res.json());
        } catch (error) {
          setError(error);
        }
      };
      fetchData();
    }, []);

    return { response, error };
  };

  export { useFetch } 

我现在得到的唯一警告是有关缺少依赖项警告的信息,但是我不确定如何解决它。我应该将所有依赖项传递到useEffect()的方括号中吗?我不确定吗? Line 27: React Hook React.useEffect has missing dependencies: 'apiUrl', 'body', 'global.apiUrl', 'headers', 'method', and 'url'. Either include them or remove the dependency array

1 个答案:

答案 0 :(得分:3)

您将收到此警告,因为根据挂钩规则,自定义挂钩名称必须以use开头。

如所提到的docs of custom hooks

  

自定义的Hook是一个JavaScript函数,其名称以“ use”开头   并且可能会称为其他挂钩。

如果将钩子重命名为

,则不会收到错误消息
const useFetchHook = async(url: string, bearer: string, method: string, body: any ) => {
    const { global } = useContext(Context) as {global: any};
    let headers = {'cache-control': 'no-cache', 'Content-Type': 'application/json' };
    if (bearer) headers = {...headers, ...{'Authorization': bearer}}
    if (method === 'GET') return await fetch(global.apiUrl + url, {method, headers});
    else return await fetch(global.apiUrl + url, {method, headers, body});
}

export { useFetchHook }

还必须记住的一件事是,如果直接在自定义钩子中执行异步代码,它将在每个渲染器上执行。更好的方法是维护状态并获取useEffect中的数据,并在接收到数据时更新状态。