简体   繁体   English

清理组件状态 useEffect

[英]Cleaning component states useEffect

I have states :我有状态:

  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);

and 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]);

When component change (by id), I would like to clean/reset all states.当组件更改(通过 id)时,我想清除/重置所有状态。 My problem is that all states are still the same, this setState functions in useEffect cleaning function doesn't work.我的问题是所有状态都一样,useEffect清理函数中的这个setState函数不起作用。

@@UPDATE @@更新

 // 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."));
  };

if your component isnt unmounted, then the return function inside useEffect will not be called.如果您的组件未卸载,则不会调用 useEffect 中的返回函数。

if only the "id" changes, then try doing this instead:如果只有“id”发生变化,请尝试这样做:

useEffect(() => {
    // ... other stuff
    setHasMore(true);
    setLastPostDate(null);
    setPosts([]);
 
    return () => { //...code to run on unmount }
},[id]);

whenever id changes, the codes inside useEffect will run.每当 id 更改时, useEffect 中的代码就会运行。 thus clearing out your states.从而清除你的状态。

OK, I fixed it, don't know if it is the best solution, but works...好的,我修复了它,不知道它是否是最好的解决方案,但是有效...

  useEffect(() => {
    setPosts([]);
    setHasMore(true);
    setLastPostDate(null);
    return () => {
      mounted = false;
      return;
    };
  }, [id]);

  // getting posts from server with first render
  useEffect(() => {
    console.log(lastPostDate, hasMore);
    hasMore && !lastPostDate && fetchPosts();
  }, [lastPostDate, hasMore]);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM