在useEffect中使用自定义钩子

时间:2020-07-28 12:37:18

标签: reactjs react-hooks

我正在尝试使用自定义的Axios挂钩来获取一些数据,但出现一条错误消息,提示“无效的挂钩调用。挂钩只能在功能组件的主体内部调用。我知道这听起来很明显,但是从某种意义上说,这没有什么意义。

这是钩子:

import { useState } from "react";
import axios from "axios";

export default useApi = () => {
  const [data, setData] = useState([]);
  const [error, setError] = useState(false);
  const [loading, setLoading] = useState(false);

  const request = async () => {
    const source = axios.CancelToken.source();
    setLoading(true);

    try {
      const response = await axios.get(url, { cancelToken: source.token });
      setData(response.data);
      setLoading(false);
    } catch (error) {
      if (axios.isCancel(error)) {
        // don't update state in case component is dismounting
        console.log("cancelled");
      } else {
        setLoading(false);
        setError(error);
      }
    }

    return () => {
      source.cancel();
    };
  };

  return { data, error, loading, request };
};

我希望能够像返回一样使用数据,错误,加载和请求,所以我尝试使用解构。

import React, { useEffect } from "react";
import useApi from "../hooks/http-hook";
const { request, data, error, loading } = useApi();


const SomeComponent = (props) => {

    useEffect(() => {
      const getUsers = async () => {
        try {
          const res = await request("http://localhost:8000/api/users");
          console.log(res);
        } catch (err) {
          console.log(err);
        }
      };
      getUsers();
    }, [request]);
}

export default SomeComponent;

1 个答案:

答案 0 :(得分:0)

您必须在组件内部使用挂钩。

我看到您正在尝试在导入后面调用它,并且我认为它在任何类型的组件之外。尝试类似

import useApi from "../hooks/http-hook";

const YourComponent = () => {
    const { request, data, error, loading } = useApi();
    console.log(request, data, error, loading);
    return <Stuff/>
}