【发布时间】:2021-05-28 22:56:26
【问题描述】:
从 api 获取 /Vehicles 后,我想在组件中显示它们,但在 useFetch 函数中我可以 console.log res.data 但在卡车组件中我无法映射卡车。
我的自定义 useFetch 函数:
import { useState, useEffect } from 'react';
import axios from 'axios';
const useFetch = (url) => {
const api = axios.create({
baseURL: 'api url',
headers: { Authorization: `Bearer ${localStorage.token}` },
});
const [data, setData] = useState(null);
const [isPending, setIsPending] = useState(true);
const [error, setError] = useState(null);
useEffect(() => {
const abortCont = new AbortController();
setTimeout(() => {
api
.get(url)
.then((res) => {
console.log(res.data);
if (!res.ok) {
throw Error('Could not with fetch data');
}
})
.then((data) => {
data.json();
console.log(data);
setIsPending(false);
setError(null);
})
.catch((err) => {
if (err.name === 'AbortError') {
console.log('fetch aborted');
} else {
setIsPending(false);
setError(err.message);
}
});
}, 1000);
return () => abortCont.abort();
}, [url]);
return { data, isPending, error };
};
export default useFetch;
我使用了这个自定义的 useFetch 函数,并且可以获取数据(在函数内部)它不能用于渲染 我认为的一些可能的原因;
- useFetch 函数可能无法正确返回数据
- 我可能需要对 API 响应使用 stringify 或 json 函数
卡车组件:
const Trucks = () => {
const { data: trucks, error, isPending } = useFetch('/vehicles');//
console.log('they are ' + { trucks }); //console output ->[object,Object]
return (Some Jsx)};
export default Trucks;
谢谢
【问题讨论】:
标签: reactjs axios react-hooks fetch-api react-component