繁体   English   中英

传递 Redux 选择器值以反应 state 而无需在 useEffect 中重新渲染

[英]Pass Redux selector value to react state without rerendering in useEffect

我想建立简单的滚动分页,所以我用 oldState 更新 currentState 并将新数据添加到旧 state,同时这个新数据来自 redux 选择器,

const Posts = () => {
  const [page, setpage] = useState(1);
  const [currentPosts, setCurrentPosts]: any = useState([]);
  const dispatch = useDispatch();

  const postList = useSelector((state: any) => state.posts);
  const { loading = true, error, posts = [] }: IPostList = postList;

  const handleClick = (id: number) => {
    dispatch(listComments(id));
  };
  const handleScroll = (event: any) => {
    const { scrollTop, clientHeight, scrollHeight } = event.currentTarget;
    if (scrollHeight - scrollTop === clientHeight) {
      setpage((prev) => prev + 1);
    }
  };

  useEffect(() => {
    dispatch(listPosts(page));
    setCurrentPosts((prev: any) => [...prev, ...posts]);
  }, [dispatch, page, posts]);

  return (
    <div onScroll={handleScroll} className="posts">
      {posts.map((post, index) => (
        <PostCard
          onClick={() => handleClick(post.id)}
          data={post}
          key={index}
        />
      ))}
    </div>
  );
};

export default Posts;

我知道它会导致无限循环,因为每当更新帖子时,都会调用 listPosts,然后它会一次又一次地更新。

Can you provide me with the right solution and explanation on how to update currentPosts state while spreading the old state and new state which comes from the redux selector? 我认为代码比我的解释更能说明问题。

你能把它作为两种不同的效果来运行吗? 我相信这应该消除无限循环。

useEffect(() => {
  dispatch(listPosts(page));
}, [dispatch, page]);

useEffect(() => {
  setCurrentPosts((prev: any) => [...prev, ...posts]);
}, [posts]);

暂无
暂无

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

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