【问题标题】:fetching more data with load more button without losing previous data redux使用加载更多按钮获取更多数据而不会丢失以前的数据
【发布时间】:2021-12-06 22:03:19
【问题描述】:

我想一次只加载 10 个帖子,当我按下加载更多按钮时,我想在前 10 个帖子的基础上再获得 10 个帖子。截至目前,当我按下加载更多时,我得到了我的前 10 个帖子,我失去了我的前 10 个并获得了第二个 10。我正在使用 redux,所以它对我来说有点困惑。我在这里读到过在我的减速器中使用concat,但它仍然不起作用。也许我的语法错误?那个帖子是 2017 年的。

  const [page, setPage] = useState(1);

  const dispatch = useDispatch();
  const { loading, posts } = useSelector((state) => state.posts);

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

  return (
    <Container className="mt-4" style={{ maxWidth: "600px" }}>
      {loading ? (
        <Loader />
      ) : (
        <>
          {posts.map((post) => (
            <Col key={post._id} className="m-2 p-2">
              <Post post={post} />
            </Col>
          ))}
          <Button onClick={() => setPage(page + 1)}>Load More</Button>
        </>
      )}
    </Container>
  );
};

我的减速器

export const postsReducer = (state = { posts: [] }, action) => {
  switch (action.type) {
    case PC.FETCH_ALL_POSTS_REQUEST:
      return { loading: true, posts: [] };
    case PC.FETCH_ALL_POSTS_SUCCESS:
      return {
        loading: false,
        posts: state.posts.concat(action.payload),
      };
    case PC.FETCH_ALL_POSTS_FAIL:
      return { loading: false, error: action.payload };

【问题讨论】:

    标签: reactjs redux pagination infinite-scroll


    【解决方案1】:

    我的假设是,在您的 getPosts 操作中,您似乎正在调度 PC.FETCH_ALL_POSTS_REQUEST,它最初将 post 设置为空数组。您可能只想将其更改为 return { loading: true } 而无需将帖子设置为 []。所以你的减速器看起来像这样

    export const postsReducer = (state = { posts: [] }, action) => {
      switch (action.type) {
        case PC.FETCH_ALL_POSTS_REQUEST:
          return { loading: true };
        case PC.FETCH_ALL_POSTS_SUCCESS:
          return {
            loading: false,
            posts: [...state.posts, ...action.payload],
          };
        case PC.FETCH_ALL_POSTS_FAIL:
          return { loading: false, error: action.payload };
    

    另外,您可能需要确认 redux 存储在新的 post fetch 上没有被清除

    【讨论】:

    • 你怎么知道我什至没有表现出我的行为?你的传奇。非常感谢!
    猜你喜欢
    • 2020-10-03
    • 2019-04-22
    • 2015-11-22
    • 1970-01-01
    • 2021-10-23
    • 1970-01-01
    • 2018-08-23
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多