实现功能

  • 传递参数调用ajax请求获取数据
  • 返回数据,loading,错误信息

    useAxios hooks

    ```jsx // useAxios hook import { useState, useEffect } from ‘react’; import axios from ‘axios’;

axios.defaults.baseURL = ‘https://jsonplaceholder.typicode.com‘;

const useAxios = ({ url, method, body = null, headers = null }) => { const [response, setResponse] = useState(null); const [error, setError] = useState(‘’); const [loading, setloading] = useState(true);

  1. const fetchData = () => {
  2. axios[method](url, JSON.parse(headers), JSON.parse(body))
  3. .then((res) => {
  4. setResponse(res.data);
  5. })
  6. .catch((err) => {
  7. setError(err);
  8. })
  9. .finally(() => {
  10. setloading(false);
  11. });
  12. };
  13. useEffect(() => {
  14. fetchData();
  15. }, [method, url, body, headers]);
  16. return { response, error, loading };

};

export default useAxios;

<a name="tjSGZ"></a>
### 使用
```jsx
// App Component

const App = () => {
      // response和loading可以直接用,页面也会响应,不需要二次手动setState
    const { response, loading, error } = useAxios({
        method: 'post',
        url: '/posts',
        headers: JSON.stringify({ accept: '*/*' }),
        body: JSON.stringify({
            userId: 1,
            id: 19392,
            title: 'title',
            body: 'Sample text',
        }),
    });
    const [data, setData] = useState([]);

    useEffect(() => {
        if (response !== null) {
            setData(response);
        }
    }, [response]);

    return (
        <div className='App'>
            <h1>Posts</h1>

            {loading ? (
                <p>loading...</p>
            ) : (
                <div>
                    {error && (
                        <div>
                            <p>{error.message}</p>
                        </div>
                    )}
                    <div>{data && <p>{data.id}</p>}</div>
                </div>
            )}
        </div>
    );
};

export default App;

为什么使用hooks

同样的封装到request.js一个function也可以返回数据返回、error、loading,为什么要多此一举的写一个hooks呢?
关键在于这个返回的loading是可以调用视图响应的!而如果是只是在request返回一个loading态,视图拿到这个状态直接使用是不会响应的,还得做二次处理。

// 使用示例
const { response, loading, error } = useAxios({});
<Button loading={loading}>点击这里</Button>

// useAxios hook
import { useState, useEffect } from "react";
const useAxios = ({ url, method, body = null, headers = null }) => {
  const [response, setResponse] = useState(null);
  const [error, setError] = useState("");
  const [loading, setLoading] = useState(false);
    const fetchData = () => {
    };
  setInterval(() => {
    let flag = !loading;
    console.log(loading, flag);
    setLoading(flag);
  }, 2000);
  useEffect(() => {
    fetchData();
  }, [method, url, body, headers]);
  return { response, error, loading };
};
export default useAxios;

这个loading已useState声明的状态,它的改变是可以使视图重新render的!
state也是,无需再在视图上进行setState触发render了~

原文
https://dev.to/ms_yogii/useaxios-a-simple-custom-hook-for-calling-apis-using-axios-2dkj