blog
blog copied to clipboard
写一个Hook发送请求
import React, { useState } from 'react';
function useFetchData(url, timeout) {
const [data, setData] = useState([]);
const [loading, setLoading] = useState(false)
const [error, setError] = useState(false)
function init() {
setData([])
setLoading(true)
setError(false)
}
async function load() {
init()
setLoading(true);
try {
const instance = axios.create();
const result = await instance.get(url, { timeout });
setData(result)
} catch (error) {
setError(true)
}
setLoading(false)
}
return [data, loading, error, load]
}