将以前的状态附加到 Redux 中的新状态

Append Previous State to New State in Redux

我有这个应用程序,它使用第一个 createAsyncThunk 从 API 获取第一页,然后我想要第二个 createAsyncThunk,它获取下一页,触发当用户到达页面底部并在无限滚动方法中获取数据时。

// Gets the First 10 Posts from the API
export const getPosts = createAsyncThunk(
  "post/getPosts",
  async (apiAddress) => {
    const response = await fetch(apiAddress);
    if (!response.ok) throw new Error("Request Failed!");
    const data = await response.json();
    return data;
  }
);

// Loads the Next 10 Posts
export const getMorePosts = createAsyncThunk(
  "post/getMorePosts",
  async (apiAddress) => {
    const response = await fetch(apiAddress);
    if (!response.ok) throw new Error("Request Failed!");
    const data = await response.json();
    return data;
  }
);

const redditPostSlice = createSlice({
  name: "post",
  initialState: {
    redditPost: {},
    isLoading: false,
    hasError: false,
    moreIsLoading: false,
    moreHasError: false,
  },
  extraReducers: (builder) => {
    builder
      .addCase(getPosts.pending, (state) => {
        state.isLoading = true;
        state.hasError = false;
      })
      .addCase(getPosts.fulfilled, (state, action) => {
        state.redditPost = action.payload.data;
        state.isLoading = false;
        state.hasError = false;
      })
      .addCase(getPosts.rejected, (state) => {
        state.isLoading = false;
        state.hasError = true;
      })
      .addCase(getMorePosts.pending, (state) => {
        state.moreIsLoading = true;
        state.moreHasError = false;
      })
      .addCase(getMorePosts.fulfilled, (state, action) => {
        state.redditPost = action.payload.data;
        state.moreIsLoading = false;
        state.moreHasError = false;
      })
      .addCase(getMorePosts.rejected, (state) => {
        state.moreIsLoading = false;
        state.moreHasError = true;
      });
  },
});

我的问题是应用的状态变成了第二页,第一页的内容不见了。

我知道我的问题出在这里 state.redditPost = action.payload.data 但我不知道如何将这个新状态附加到前一个状态。

我已经在这里待了几个小时了,真的不知道该怎么做了。

有什么方法可以将新状态附加到以前的状态吗?

我假设负载数据有一个子数组。就像网上找到的这个回复例子:

{
   kind: "Listing",
   data: {
      ...
      children: [
          {kind: "t3", data: {...}}
          {kind: "t3", data: {...}}
          {kind: "t3", data: {...}}
          ...
      ]
      ...
   }
}

所以你需要让 redditPost 成为一个数组。在语义上也应该是 redditPosts 来表示数组。

  initialState: {
    redditPost: {},
    ...

然后当你更新它时,最简单的方法之一就是使用 ES6 spread

state.redditPost = {
    ...state.redditPost,
    after: action.payload.data.after,
    children: [
        ...state.redditPost.children,
        ...action.payload.data.children
    ]
}