将先前状态追加到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排列

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

相关文章