javascript - 清理组件状态 useEffect
问题描述
我有状态:
const { id } = useParams<IRouterParams>();
const [posts, setPosts] = useState<IPost[]>([]);
const [perPage, setPerPage] = useState(5);
const [fetchError, setFetchError] = useState("");
const [lastPostDate, setLastPostDate] = useState<string | null>(null);
// is any more posts in database
const [hasMore, setHasMore] = useState(true);
和 useEffect :
// getting posts from server with first render
useEffect(() => {
console.log(posts);
fetchPosts();
console.log(hasMore, lastPostDate);
return () => {
setHasMore(true);
setLastPostDate(null);
setPosts([]);
mounted = false;
return;
};
}, [id]);
当组件更改(通过 id)时,我想清理/重置所有状态。我的问题是所有状态都还是一样,useEffect 清理函数中的这个 setState 函数不起作用。
@@更新
// getting posts from server
const fetchPosts = () => {
let url;
if (lastPostDate)
url = `http://localhost:5000/api/posts/getPosts/profile/${id}?limit=${perPage}&date=${lastPostDate}`;
else
url = `http://localhost:5000/api/posts/getPosts/profile/${id}?limit=${perPage}`;
api
.get(url, {
headers: authenticationHeader(),
})
.then((resp) => {
if (mounted) {
if (resp.data.length === 0) {
setFetchError("");
setHasMore(false);
setPosts(resp.data);
return;
}
setPosts((prevState) => [...prevState, ...resp.data]);
if (resp.data.length < perPage) setHasMore(false);
setLastPostDate(resp.data[resp.data.length - 1].created_at);
setFetchError("");
}
})
.catch((err) => setFetchError("Problem z pobraniem postów."));
};
解决方案
如果您的组件未卸载,则不会调用 useEffect 中的返回函数。
如果只有“id”发生变化,请尝试这样做:
useEffect(() => {
// ... other stuff
setHasMore(true);
setLastPostDate(null);
setPosts([]);
return () => { //...code to run on unmount }
},[id]);
每当 id 更改时,useEffect 中的代码就会运行。从而清除您的状态。
推荐阅读
- json - 使用 Spark 2.4 识别空 JSON 文件
- c# - 在 Unity 中捕获 360 度屏幕截图会忽略 UI 层
- sql - 如何将一个 SQL 列转换为同一行的多个列?
- java - 在 Android 中,我如何实现一个全局触摸跟踪服务,即使屏幕上正在运行其他应用程序也能正常工作
- java - Spring Boot 配置问题中的 JWT 令牌
- oracle - 在 SQL Developer 中使用 DESCRIBE 获取其数据类型的列列表时如何按列名排序?
- r - R ShinyDashBoard 布局列布局
- apache-spark - 在 Docker 中运行 Spark 历史服务器以查看 AWS Glue 作业
- testrail - TestRail API 返回 HTTP 429("API Rate Limit Exceeded - 180 per minute maximum allowed. Retry after 1 seconds.")
- c - C:如何在另一个函数B中使用在函数A中声明和定义的结构