我可以在控制台中看到我的数据,但不能在 React.js 的 UI 上看到我的数据,问题出在哪里?
import { useEffect, useState } from "react";
const useFetch = () => {
const [data, setData] = useState(null);
const [isPending, setIsPending] = useState(true);
const [error, setError] = useState(null);
useEffect(() => {
const abortCont = new AbortController()
setTimeout(() => {
fetch('http://localhost:3000/blogs', {signal: AbortController.signal})
.then(res => {
console.log(res)
if(!res.ok){
throw Error('Could no fetch the data for that resource')
}
return res.json();
})
.then(data => {
setData(data)
console.log(data)
setIsPending(false)
setError(null)
})
.catch(err => {
if(err.name === 'AbortError')
console.log('fetch aborted')
setIsPending(false)
setError(err.message)
}, 1000)
});
return() => abortCont.abort()
}, []);
return {data, isPending, error}
}
export default useFetch;
我试图通过 ID 查看我的博客,但收到一个空白页面。
试试这个
import { useEffect, useState } from "react";
const useFetch = () => {
const [data, setData] = useState(null);
const [isPending, setIsPending] = useState(true);
const [error, setError] = useState(null);
useEffect(() => {
const abortCont = new AbortController();
setTimeout(() => {
fetch("http://localhost:3000/blogs", { signal: abortCont.signal })
.then((res) => {
console.log(res);
if (!res.ok) {
throw Error("Could not fetch the data for that resource");
}
return res.json();
})
.then((data) => {
setData(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();
}, []);
return { data, isPending, error };
};
export default useFetch;
您的代码中有一个小错误。您正在利用时间值 catch 块,但您可以在 setTimeout 中使用它。
import { useEffect, useState } from "react";
const useFetch = () => {
const [data, setData] = useState(null);
const [isPending, setIsPending] = useState(true);
const [error, setError] = useState(null);
useEffect(() => {
const abortCont = new AbortController()
setTimeout(() => {
fetch('http://localhost:3000/blogs', {signal: AbortController.signal})
.then(res => {
console.log(res)
if(!res.ok){
throw Error('Could no fetch the data for that resource')
}
return res.json();
})
.then(data => {
setData(data)
console.log(data)
setIsPending(false)
setError(null)
})
.catch(err => {
if(err.name === 'AbortError')
console.log('fetch aborted')
setIsPending(false)
setError(err.message)
})
},1000);
return() => abortCont.abort()
}, []);
return {data, isPending, error}
}
export default useFetch;