【发布时间】:2021-10-19 17:09:32
【问题描述】:
我想使用这个自定义钩子来发出 api 请求:
export default function useFetch({ method, url, data = null, config = null }) {
const [response, setResponse] = useState(null);
const [error, setError] = useState("");
const [isLoading, setIsLoading] = useState(true);
useEffect(() => {
const fetchData = async () => {
try {
api[method](url, JSON.parse(config), JSON.parse(data))
.then((res) => {
setResponse(res.data);
})
.finally(() => {
setIsLoading(false);
});
} catch (err) {
setError(err);
}
};
fetchData();
}, [api, method, url, data, config]);
return { response, error, isLoading };
}
上面的代码并不重要。所以不要太在意它。我的问题是如何在同一个组件中进行两个 api 调用。这可能吗?
export const programApi = axios.create({
baseURL: programApiUrl,
});
const {response, isLoading} = useFetch({
api: programApi,
method: "get",
url: "/SportsProgram/active_sport_type",
config: JSON.stringify({ requireAuthentication: true }),
});
useEffect(() => {
if (response !== null) {
// do more stuff if you wish
}
}, [response]);
useFetch可以使用两次吗?
【问题讨论】:
标签: reactjs react-hooks