首先我要说的是,React 我是一个初学者,我真正不明白的是为什么我无法获取 2 个端点,所以它们检索我的数据,然后我可以在我的不同组件中使用它
这是我的App.jsx
import { Route, Routes } from 'react-router-dom';
import useFetch from './hooks/useFetch';
import { BlogContentPage, Homepage } from './pages';
import AboutPage from './pages/AboutPage';
export default function App() {
let { loading, data, error } = useFetch('http://localhost:1337/api/blogs?populate=*'); // this one is ok, is recieving data.
let { data: authors } = useFetch('http://localhost:1337/api/authors?populate=*'); // this one is not, and if I remove the one above this one works (!?!?!)
if (loading) return <p>Loading...</p>;
if (error) return <p>Error!</p>;
console.log(authors); // this is null..
return (
<div>
<Routes>
<Route path='/' element={<Homepage blogs={data ? data : ''} />}></Route>
<Route path='/blog/:id' element={<BlogContentPage blogs={data ? data : ''} />}></Route>
<Route path='/about' element={<AboutPage authors={authors ? authors : ''} />}></Route>
</Routes>
</div>
);
}
这是我的 useFetch 自定义 Hook(可能我在这里做错了什么)..
import { useEffect, useState } from 'react';
const useFetch = (url) => {
const [data, setData] = useState(null);
const [error, setError] = useState(null);
const [loading, setLoading] = useState(true);
useEffect(() => {
const fetchData = async () => {
setLoading(true);
try {
const res = await fetch(url);
const json = await res.json();
setData(json);
setLoading(false);
} catch (error) {
setError(error);
setLoading(false);
}
};
fetchData();
}, [url]);
return { loading, error, data };
};
export default useFetch;
我的期望是我编写的 useFetch 钩子每次被调用时都会起作用。
那么您可以重构自定义挂钩以接受多个端点
import { useEffect, useState } from 'react';
const useFetch = (urls) => {
const [data, setData] = useState([]);
const [error, setError] = useState(null);
const [loading, setLoading] = useState(true);
useEffect(() => {
const fetchData = async () => {
setLoading(true);
try {
const promises = urls.map(async (url) => {
const res = await fetch(url);
return res.json();
});
const results = await Promise.all(promises);
setData(results);
setLoading(false);
} catch (error) {
setError(error);
setLoading(false);
}
};
fetchData();
}, [urls]);
return { loading, error, data };
};
export default useFetch;
在你的主文件中你可以这样使用它
const { loading, data: blogData, error } = useFetch(['http://localhost:1337/api/blogs?populate=*', 'http://localhost:1337/api/authors?populate=*']);
if (loading) return <p>Loading...</p>;
if (error) return <p>Error!</p>;