在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
]
}

相关内容

  • 没有找到相关文章

最新更新