1 回答
TA贡献1820条经验 获得超2个赞
请检查这个例子。这里我在 useEffect 中调用 axios 并在 ui 中显示响应数据。
import React, {useEffect, useState} from "react";
import axios from 'axios';
function PostListPage() {
const [posts, setPost] = useState([]);
let signal = axios.CancelToken.source();
useEffect(() => {
let isSubscribed = true;
axios.get(`https://jsonplaceholder.typicode.com/posts`, {
cancelToken: signal.token,
})
.then(res => {
const posts = res.data;
setPost(posts);
}).catch(err => {
console.log(err);
});
return function cleanup() {
isSubscribed = false;
signal.cancel('Api is being canceled');
}
}, []);
return (
<React.Fragment>
<ul>
{
posts.map(post => <li key={post.id}>{post.title}</li>)
}
</ul>
</React.Fragment>
);
}
export default PostListPage;
添加回答
举报