我使用 React With TypeScript 创建了简单的博客网站,我制作了一个服装钩子( useFetch )这个钩子在 UseEffect 钩子内部获取数据..这是代码:
const useFetch = (url : string) => {
interface Blogs{
title:string,
body:string,
author?:string,
id:number;
}
const [data , setData] = useState<Blogs[] | null>(null)
const [isPending , setIsPending] = useState<boolean>(true)
const [error , setIsError] = useState(null)
useEffect(()=>{
const controller = new AbortController();
// const signal = controller.signal;
setTimeout(() => {
fetch(url , {signal:controller.signal})
.then(res=> res.json())
.then(data=> {
setData(data)
setIsPending(false)
}).catch(err=>{
if(err.message === "AbortError"){
console.log("Fetch Aborted");
}else{
setIsError(err.message)
setIsPending(false)
}
})
}, 1000);
return ()=>controller.abort();
} , [url])
return { data , isPending , error}
}
我刚刚添加 setTimeOut 来检查中止控制器是否工作.. 问题是获取是带来数据然后它是捕获.. 带有此消息:信号无故中止 原始 content.tsx 代码:
function Content(){
const {data : blogs , isPending , error} = useFetch("http://localhost:800/blogs");
let [name , setName] = useState("Eshada");
function handleClick():void {
name = "Essam"
setName("Essam")
console.log(`Hello mr ${name} it's nice to meet you !!`);
}
return(
<div className="content">
<div className="container">
<div className="articles-container">
{isPending && <div> Loading...</div>}
{error && <div> Some Thing went wrong : {error} </div>}
{blogs && <BlogList name ="All Blogs" blogs = {blogs}/>}
</div>
<button onClick={handleClick}>Click Me!</button>
</div>
</div>
)
}
我发现了,我只是将我的 Catch 代码更改为
.catch((err) => {
if (err.name === 'AbortError') {
console.log('Fetch aborted');
} else {
setError(err.message);
setIsPending(false);
}
});
它的工作..在检查err.message的行中我尝试了err.name并且它的工作!