一个简单的ajax请求hooks useAxios
实现功能传递参数调用ajax请求获取数据返回数据,loading,错误信息useAxios hooks// useAxios hookimport { useState, useEffect } from 'react';import axios from 'axios';axios.defaults.baseURL = 'https://jsonplaceholder.typicode.com'
·
实现功能
- 传递参数调用ajax请求获取数据
- 返回数据,loading,错误信息
useAxios hooks
// 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);
const fetchData = () => {
axios[method](url, JSON.parse(headers), JSON.parse(body))
.then((res) => {
setResponse(res.data);
})
.catch((err) => {
setError(err);
})
.finally(() => {
setloading(false);
});
};
useEffect(() => {
fetchData();
}, [method, url, body, headers]);
return { response, error, loading };
};
export default useAxios;
使用
// App Component
const App = () => {
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
更多推荐
已为社区贡献3条内容
所有评论(0)